I am creating a static function that checks if the user email for registration is in use. If the email is in use the function should return true
otherwise false
.
The code I have is returning always false
and seems that the variable I use is not updated.
Any Idea what am I doing wrong and why is this not working as expected?
class userInfo: NSObject {
static func userRegistration(email: String) -> Bool {
var emailIsavailable = false
Alamofire.request(.GET, "https://example/check_email.php?email=\(email)")
.responseString{ response in
if let responseValue = response.result.value {
print("Response String: \(responseValue)")
if responseValue == "email is available"{
print("email available")
emailIsavailable = true //emailIsavailable is not updated
}else{
print("email not available")
emailIsavailable = false //emailIsavailable is not updated
}
}
}
return emailIsavailable // returns always false
}
}
Because it run in different thread so you can't return straight. You should use callback (or another call block, closure). You should edit code:
class userInfo: NSObject {
static func userRegistration(email: String, callBack : (emailIsavailable : Bool) -> Void) {
Alamofire.request(.GET, "https://example/check_email.php?email=\(email)")
.responseString{ response in
if let responseValue = response.result.value {
print("Response String: \(responseValue)")
if responseValue == "email is available"{
print("email available")
callBack(emailIsavailable: true)
}else{
print("email not available")
callBack(emailIsavailable: false)
}
}
}
}
}
And you can call like:
yourInstance.userRegistration("test") { (emailIsavailable) -> Void in
//you can get emailIsavaiable or something here
}