xcode 如何从FirestoreMap用户数据

thtygnil  于 2022-11-18  发布在  其他
关注(0)|答案(1)|浏览(199)

我试图通过.map获取用户的年龄和用户名,但它显示的是最后一个用户登录信息,而不是当前用户。
我很确定问题出在snapshot.data().map中,但我不知道如何将其更改为当前用户。

func getData() {

        let db = FirebaseManager.shared.firestore
        
        guard let uid = FirebaseManager.shared.auth.currentUser?.uid
        else {
            self.errorMessage = "Could not find firebase uid"
            return
        }
        
        db.collection("user").document(uid).getDocument { snapshot, error in
            
            if error == nil {
                //No errors
                
                if let snapshot = snapshot {
                    
                    DispatchQueue.main.async { 

                        self.userInfo = snapshot.data().map { d in
                            
                            return UserInfo(age: d["age"] as? Int ?? 18, username: d["username"] as? String ?? "")
                        }
                    }
                }
            } else {
                self.errorMessage = "Uh Oh... Error"
            }
        }
    }

在视图中,我将其显示为:
Text("\(userMng.userInfo?.username ?? "NoUsername"), \(userMng.userInfo?.age ?? 18)")

bxjv4tth

bxjv4tth1#

要获取当前登录用户数据,您需要一个模型。
模型示例:

struct User{
    var uid: String 
    var name: String
    var surname: String
    var username: String
    var email: String
    var gender: String
    var age: Int

}

然后,您将需要一个viewModel来将您的模型和视图连接在一起,这里是您将执行firebase调用的地方。
视图模型示例:

import Foundation
import FirebaseFirestore

class SignedInUser: ObservableObject{
    
    private var auth = Auth.auth()
    private var db = Firestore.firestore()
    @Published var user: User?
    
    
    init(){
        fetchCurrentUser()
    }
    
    private func fetchCurrentUser(){
      
        guard let uid = auth.currentUser?.uid else {
            return
        }

        db.collection("users").document(uid).getDocument(completion: { (snapshot, error) in
            if let error = error{
                print("Failed to fetch current user", error.localizedDescription)
                return
            }
            
            guard let data = snapshot?.data() else{ return }
            
            let uid = data["uid"] as? String ?? ""
            let name = data["name"] as? String ?? ""
            let surname = data["surname"] as? String ?? ""
            let username = data["username"] as? String ?? ""
            let email = data["email"] as? String ?? ""
            let gender = data["gender"] as? String ?? ""
            let age = data["age"] as? Int ?? 0
            
            self.user = User(uid: uid, name: name, surname: surname, username: username, email: email, gender: gender, age: age)

            
            
        })
    }

在那里,您将通过获取登录用户的uid并在firebase中搜索它来获取当前用户,然后您将检查错误,如果成功,您将为数据调用snapshotquery,当您获得数据时,您将Map出所有数据并将其设置为User。
然后可以在视图中使用该用户。
视图示例:

import SwiftUI
import FirebaseAuth

struct HomeScreenView: View {
    @ObservedObject private var vm = SignedInUser()
    var body: some View {
        ZStack{
            Color("BG")
                .ignoresSafeArea()
            VStack{
                Text("Current user: \(vm.user?.name ?? "")")
                Text("Home View")
                Text("\(Auth.auth().currentUser?.uid ?? "")")
                Button(action: {
                    try? Auth.auth().signOut()
                }, label: {
                    Text("Logout")
                })
            }//VStack
        }//ZStack

        
    }
}

struct HomeScreenView_Previews: PreviewProvider {
    static var previews: some View {
        HomeScreenView()
    }
}

希望这对你有帮助。

相关问题