Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

making an asynchronous alamofire request synchronous

Tags:

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.

like image 785
mark Avatar asked Apr 25 '16 15:04

mark


1 Answers

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)
}
like image 104
vadian Avatar answered Sep 28 '22 04:09

vadian