I have this function which has a completion block, the function returns asynchronously without waiting for the completion.
I want my function to delay its return till its completion block is finished. I changed my function for callbacks, it doesn't work, I am new to swift so have little idea of GCD, also their API has also changed a lot.
func authenticateCredentials(usernameString: String, passwordString: String, completion: @escaping (Bool)-> Void) {
var boolVal: Bool = false
client.invokeAPI("AuthenticateAndFetchData",
body: nil,
httpMethod: "GET",
parameters: ["userid": usernameString,"password":passwordString],
headers: nil)
{
(result, response, error) -> Void in
if let err = error {
print("ERROR ", err)
} else if let res = result {
let jsonArray = res as! NSArray
// print(jsonArray)
for value in jsonArray[0] as! NSDictionary {
let jsonstring = value.value as! String
NetworkService.jsonResponse = jsonstring
if let data = jsonstring.data(using: .utf8) {
if let content = try? JSONSerialization.jsonObject(with: data, options: []),
let array = content as? [[String: Any]]
{
for jsondict in array {
let auth = jsondict["IsAuth"]! as! String
print(type(of: auth))
print(auth)
boolVal = (auth == "true") ? true : false
self.isAuth = boolVal
print(boolVal)
completion(boolVal) // callback here
}
}
}
}
}
}
}
I am calling this function from my viewController on login action like this.
// After login button is pressed
@IBAction func loginButtonTapped(_ sender: UIButton) {
let userid = userIDtxt.text
let password = userpasswordtxt.text
//Display an alert if no text is entered
if (userid?.isEmpty)! || (password?.isEmpty)! {
displayAlertMessage("Please enter userid/password")
}
// take this userid and password and authenticate from sql server and move to
else {
// Run the spinner to show the task is in progress
print("\(userid)" + " " + "\(password)")
nw.authenticateCredentials(usernameString: userid!, passwordString: password!){
(boolVal) in
self.nw.isAuth = boolVal
}
showActivityIndicatory(uiview: view)
if nw.isAuth == true {
// User authenticated
}
else {
// wrong user
}
}
}
So here, the authenticateCredentials
function returns beforehand, and it returns false, so when I click my login button first time, I receive false, when I press it second time, I receive true. I want to receive true and authenticate user on first click.