简体   繁体   English

"SwiftUI - 从 Firebase 文档中获取字段值"

[英]SwiftUI - Get field value from a Firebase document

I'm pretty new to SwiftUI and using Firebase and have stumbled upon retrieving a value from a document on Firebase.我对 SwiftUI 和使用 Firebase 还是很陌生,并且偶然发现了从 Firebase 上的文档中检索值。 I've done some Googling but have yet to find a way to do this.我已经做了一些谷歌搜索,但还没有找到一种方法来做到这一点。

My code so far looks like this:到目前为止,我的代码如下所示:

//Test1: get user info
func readUserInfo(_ uid: String) -> String {
    let db = Firestore.firestore()
    let docRef = db.collection("users").document(uid)
    var returnThis = ""
    docRef.getDocument { (document, error) -> String in
        if let document = document, document.exists {
            let dataDescription = document.data().map(String.init(describing:)) ?? "nil"
            print("Document data: \(dataDescription)")
            returnThis = dataDescription
            return(dataDescription)
        } else {
            print("Document does not exist")
        }
    }
    return returnThis
}


//Test2: get user info
func readUserInfo(_ uid: String) -> String {
    let db = Firestore.firestore()
    let docRef = db.collection("users").document(uid)
    var property = "not found"
    docRef.getDocument { (document, error) in
        if let document = document, document.exists {
            property = document.get("phoneNumber") as! String
        }
    }
    return property
}

The reason why the value is never found is because the network request you are making takes time to retrieve that data.从未找到该值的原因是因为您发出的网络请求需要时间来检索该数据。 By the time it reaches the return statement the data from firebase has not been been retrieved yet so it will just return the value it was initially set to which was an empty string.当它到达 return 语句时,尚未检索到来自 firebase 的数据,因此它只会返回最初设置为空字符串的值。 What you should do is add a completion handler<\/a> to the function so that once the data is finally retrieved you can then return it.您应该做的是向函数添加一个完成处理程序<\/a>,以便一旦最终检索到数据,您就可以返回它。

struct ContentView: View {
    @State private var text: String = ""
    
    var body: some View {
        Text(text)
            .onAppear {
                readUserInfo("sydQu5cpteuhPEgmHepn") { text in
                    self.text = text
                }
            }
    }
    
    func readUserInfo(_ uid: String, _ completion: @escaping (String) -> Void) {
        let db = Firestore.firestore()
        let docRef = db.collection("users").document(uid)
        docRef.getDocument { document, error in
            if let document = document, document.exists {
                let dataDescription = document.data().map(String.init(describing:)) ?? "nil"
                print("Document data: \(dataDescription)")
                completion(dataDescription)
            } else {
                completion("Document does not exist")
            }
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM