简体   繁体   中英

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. I've done some Googling but have yet to find a way to do 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. 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.

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")
            }
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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