我想通过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)
}
}