I am attempting to have my program check for unique usernames. My problem right now is that it will return before completing. I understand since this is async and happening in the background; however, I have attempted using DispatchGroups and semaphores and non of which are working. This is in swift and any help would be appreciated. I am fairly new when it comes to Firestore.
func checkUsernames(_ user: String) {
let docRef = db.collection("userRI").document(user)
docRef.getDocument { (document, error) in
if let document = document, document.exists {
self.uniqueUser = false
print("does exist")
} else {
self.uniqueUser = true
print("does not exist \(self.uniqueUser)")
}
}
}
CodePudding user response:
docRef.getDocument() is asynchronous and returns immediate before the query is complete. The callback will be invoked some time later. That means your function will return before uniqueUser
has a value.
The idea to fix is to consider an escaping callback to pass the value around.
func checkUsernames(_ user: String, completion: @escaping (_ uniqueUser: Bool) -> Void) {
let docRef = db.collection("userRI").document(user)
docRef.getDocument { (document, error) in
if let document = document, document.exists {
completion(false)
print("does exist")
} else {
completion(true)
print("does not exist \(self.uniqueUser)")
}
}
}