Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

wait for response Alamofire swift

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")
    }

}
like image 675
JuicyFruit Avatar asked Sep 17 '25 17:09

JuicyFruit


2 Answers

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)
}
like image 148
Amit Singh Avatar answered Sep 20 '25 05:09

Amit Singh


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.

like image 24
Feldur Avatar answered Sep 20 '25 05:09

Feldur