4

I need to wait for response.response?.allHeaderFields data before executing function. I've searched the net and didn't quite get how to add "completion handler" to alamofire request. Or if there are any other ways to make the function wait.

@IBAction func comfirmation(sender: UIButton) {
    if CodeTextField.text != "" {
        print("in comfirmation function")
        let comfirmationRequestData = [
            "phone" : "\(appDelegate.savedNumber)",
            "code" : "\(CodeTextField.text!)"
        ]
        Alamofire.request(.POST,
            "http://192.168.214.241:4000/login",
            parameters: comfirmationRequestData,
            encoding: .JSON).responseJSON {
                response in
                switch response.result {
                case .Success:
                    let jsonDecrypted = JSON(response.result.value!)
                    print(jsonDecrypted)
                    let headerFile = response.response?.allHeaderFields as? [String:String]
                    print(headerFile)

                case .Failure(let error):
                    print(error)
                }
        }
        print("in comfirmation function. success")
        appDelegate.defaults.setValue(appDelegate.savedNumber, forKey: "phoneNumber")
    } else {
        print("in comfirmation function. failed")
    }

}
JuicyFruit
  • 2,638
  • 2
  • 18
  • 35

3 Answers3

4

Use Alamofire like this

func postRequest( urlSuffix : String, params:[String : AnyObject]?, filterParams : [String]?, success: (response: AnyObject!) -> Void, failure: (error: NSError?) -> Void)
{
    Alamofire.request(.POST, webServicesURLPrefix + urlSuffix, parameters: params, encoding: .JSON, headers: self.headers)
    request?.responseJSON { response in
        switch response.result
        {
        case .Success:
            success(response: response.result.value)
        case .Failure(let error):
            failure(error: error)
        }
    }
}

Call the method from anywhere as

self.postRequest("do-registration.php", params: params, filterParams: nil, success: { (response) -> Void in
        self.afterResponse(response)
        }) { (error) -> Void in
            failure(error: error)
    }

OR you can write a saperate method which you will have to call after the completion.

func afterResponse(responseData : AnyObject)
{
    print("Done")
    print(responseData)
}
Amit Singh
  • 2,698
  • 21
  • 49
  • still if I add print("done") in the end of the function it prints it before it prints returned data. – JuicyFruit Jun 27 '16 at 12:10
  • Yes, if you write the print method in the end of the function, it will get printed after execution of the post request. and the post request is Async operation – Amit Singh Jun 27 '16 at 12:13
  • You have to write the command inside the block, if you want it to get executed after the operation completes – Amit Singh Jun 27 '16 at 12:15
  • I'm not sure you understand what I would like to do is to make asynch Alamofire request synch. – JuicyFruit Jun 27 '16 at 12:25
  • Any specific reason for this – Amit Singh Jun 27 '16 at 12:25
  • If you do so, sync operation will make your block your UI. – Amit Singh Jun 27 '16 at 12:29
  • @AlexanderK. You have to perform the operation after you get the response. If you use Sync operation, you will not be able to perform anything on the UI which will pretend like your App hangs. So, in Async you can display a ActivityIndicator – Amit Singh Jun 27 '16 at 12:33
  • @AmitSingh I need to load some data from the server before I run my tests. – RustamG Dec 27 '16 at 09:14
1

You can cause the operation to be synchronous, but in order to do that you are going to have to use a semaphore for that you set up prior to the Alamofire request, and that you then release within the completion handler. You will wait on the semaphore right after you initiate Alamo fire.

Feldur
  • 1,121
  • 9
  • 23
  • 1
    A semaphore is as bad as a dispatch group. The Alamofire requests – as well as the `NSURLSession` equivalents – are designed to work asynchronously and are supposed to be handled accordingly. – vadian Jun 27 '16 at 13:34
  • I didn't say it was a good idea, I said it would deal with his request. No? – Feldur Jun 27 '16 at 13:58
0

There is a library Alamofire-Synchronous which works using semaphore.

Sample:

//json
let response = Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"]).responseJSON()
if let json = response.result.value {
    print(json)
}
RustamG
  • 1,815
  • 1
  • 14
  • 16