I have a function that has a function within it in terms of a call to a firebase database.
The internal function sets the value of a variable from the wrapper function, but my output does not register this. When debugging it looks like this happens in reverse order. I'm new to swift and firebase so i'm just trying to get my head round this.
This is my function and output.
func checkIfUsernameExists(inUsername: String) -> String{
var aString = "false"
let ref = FIRDatabase.database().reference()
ref.child("-KohvyrIikykRsOP0XCx").observeSingleEvent(of: .value , with: {(snapshot) in
if snapshot.hasChild(self.username.text!){
print ("*** username already exists")
aString = "true"
}
})
print ("*** value of aString is: ", aString)
return aString
}
output is:
*** value of aString is: false
*** username already exists
Edit:
I phrased my question poorly i think.
What i meant to ask was how can i get the call back from firebase before processing the information its collected. I've bounced round SO and lots of blogs all pointing to Async, GCD and Completion handlers. None of which seemed to work or were easy enough for noob to get their head round.
Needless to say i've found my answer here.
Firebase Swift 3 Completion handler Bool
This is what i used:
func checkIfUsernameExists(userid: String, completionHandler: @escaping ((_ exist : Bool) -> Void)) {
let ref = FIRDatabase.database().reference()
ref.child("-KohvyrIikykRsOP0XCx").observeSingleEvent(of: .value , with: {(snapshot) in
if snapshot.hasChild(self.username.text!){
self.usernameCheck = "true"
completionHandler(true)
}
else {
self.usernameCheck = "false"
completionHandler(true)
}
})
}