making an asynchronous alamofire request synchronous

前端 未结 1 520
时光说笑
时光说笑 2021-01-18 18:02

I am attempting to perform an alamofire post request in swift

func checkIfUserExistsInDB(userName: String) -> NSString
{

  print (\"IN\")
  var info: NSS         


        
相关标签:
1条回答
  • 2021-01-18 18:42

    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)
    }
    
    0 讨论(0)
提交回复
热议问题