限制/减少对Firebase Firestore的读取次数-Swift

时间:2020-04-25 23:02:51

标签: swift firebase if-statement google-cloud-firestore init

我想通过Firestore为我的变量“ Username”设置一个值。一旦设置了“用户名”值,我就不再需要调用Firestore。这样一来,每次用户打开配置文件页面时,它并不会每次都调用Firestore,而是第一次调用它。

有什么想法吗?

这里有一段我​​尝试使用的代码,但是我没有成功

  var username = ""

    func callToFirestore () {
        if username == "" {
            //If username has not value - set a value grabbed from Firestore
                guard let uid = Auth.auth().currentUser?.uid else { return }
                let database = Firestore.firestore().collection("Users").document(uid)
                database.getDocument { (docSnapshot, error) in
                guard let docSnapshot = docSnapshot, docSnapshot.exists else {return}
                let mydata = docSnapshot.data()
                let username = mydata!["Username"] as? String ?? ""
                self.username = username }
        } else {
            //If username != "" (meaning it has a value) - print the username
                print(username)
        }
    }

0 个答案:

没有答案