I created a login mechanism with phone number. I want to check if the phone number is already registered or not, but the function I created will always return false. How to make it wait until the task is finished and then return?
func isPhoneNumberRegistered(phoneNumber: String) -> Bool {
var isRegistered = false
DispatchQueue.main.async {
self.userData.child(phoneNumber).observeSingleEvent(of: .value, with: {(snapshot) in
if snapshot.exists(){
print("phone number exist")
isRegistered = true
}else{
print("phone number doesn't exist")
isRegistered = false
}
})
}
return isRegistered
}
2
Answers
This is a good case for using a semaphore. Just make sure not to call the function on the main queue. The main queue is a serial queue, and this on main queue will cause a deadlock.
try this simple and very common approach, using a completion handler:
and use it like this:
You can also use the Swift
async/await
for asynchronous functions.