mark mark - 7 months ago 577
Swift Question

making an asynchronous alamofire request synchronous

I am attempting to perform an alamofire post request in swift

func checkIfUserExistsInDB(userName: String) -> NSString
{

print ("IN")
var info: NSString = ""

Alamofire.request(.POST, "http://blablabla.com/getuserdata", parameters: ["queryValue": userName,], encoding:.JSON).responseJSON { request, response, result in
switch result {
case .Success(let JSON):
info = NSString(data: JSON.dataUsingEncoding(NSUTF8StringEncoding)!, encoding: NSUTF8StringEncoding)!

case .Failure(let data, _):
print ("IN")
if let data = data {
info = (NSString(data: data, encoding: NSUTF8StringEncoding)!)

print (info)
}

}
}

return info
}


but I am running into trouble making it synchronously. I am aware that making an asynchronous function (like the one provided by Alamorfire) is not generally accepted but in my case I have to do it synchronously.

Answer

It's quite easy to implement a completion block in Swift.

This is your function with a completion block

func checkIfUserExistsInDB(userName: String, completion:(String) -> Void)
{
  Alamofire.request(.POST, "http://blablabla.com/getuserdata", parameters: ["queryValue": userName,], encoding:.JSON).responseJSON { request, response, result in
    switch result {
    case .Success(let JSON):
      let info = String(data: JSON.dataUsingEncoding(NSUTF8StringEncoding)!, encoding: NSUTF8StringEncoding)!
      completion(info)

    case .Failure(let data, _):
      if let errorData = data, info = String(data: errorData, encoding: NSUTF8StringEncoding) {
        completion(info)
      }
    }
  }
}

and can be called with (info is the asynchronously returned string)

checkIfUserExistsInDB("string") { (info) in
  print(info)
}