繁体   English   中英

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

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

我对 SwiftUI 和使用 Firebase 还是很陌生,并且偶然发现了从 Firebase 上的文档中检索值。 我已经做了一些谷歌搜索,但还没有找到一种方法来做到这一点。

到目前为止,我的代码如下所示:

//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
}

从未找到该值的原因是因为您发出的网络请求需要时间来检索该数据。 当它到达 return 语句时,尚未检索到来自 firebase 的数据,因此它只会返回最初设置为空字符串的值。 您应该做的是向函数添加一个完成处理程序<\/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