How to have a completion handler/block after Alamofire Post request?

眉间皱痕 提交于 2019-12-10 15:19:48

问题


I have a method which handles a Apple Push Notification Service remote notification. When this method is executed, I want it to call my server and do a HTTP POST request using the Alamofire library. I want to execute another method that will handle the response of the POST request.

The problem for me is that I am using an existing API to fetch a profile from the server in this POST request. So I need to use this existing API and figure out when this profile fetch is specifically triggered from the remote notification.

Since Alamofire requests are done in a background queue, how would I go about doing an execution of a method after receiving the profile back from the server?

What would be a good option to solving this issue?

Thank you!


回答1:


Since Alamofire requests are done in a background queue, how would I go about doing an execution of a method after receiving the profile back from the server?

Response handling is built in to Alamofire. You can do something like this (adapted from the docs):

Alamofire.request(.POST, "http://httpbin.org/get", parameters: ["foo": "bar"])
         .response { (request, response, data, error) in
                     println(request)
                     println(response)
                     println(error)
                   }

Note the .response method call, which adds a completion handler to the request object; the completion handler is invoked by Alamofire when the request completes (or fails).




回答2:


It wasn't clear from your question formulation what problem you were trying to solve. But you've clarified your intent in the question comments above.

As I understand the problem now, you're got some code that updates a profile on the server and handles the server's response. The code is called in two contexts, one initiated by a manual request from the user, another initiated by a push notification. In the first case, you don't want to generate an alert after you process the response from the server, but in the second case you do.

You do indeed have a closure that you can use to handle the different behavior even though the difference happens in the asynchronous part of the process. Here's a sketch (not actual working code) of how that might look:

func updateProfile(parameters: [String:String], showAlert: Bool) {
    Alamofire.request(.POST, "http://myserver.com/profile", parameters: parameters)
             .response { (request, response, data, error) in
                         if (error == nil) {
                           processProfileResponse(response)
                           if showAlert {
                             showProfileWasUpdatedAlert()
                           }
                         }
                   }      

}

Note the showAlert parameter passed in to the updateProfile method. If you pass in true, it calls the showProfileWasUpdatedAlert method to show your alert after receiving the server's response. Note that this boolean value is "captured" by the closure that handles the Alamofire response because the closure was defined inside the updateProfile function.

This, IMHO, is a better approach than declaring an app global inside your AppDelegate.




回答3:


Here you go

func AlamofireRequest(method: Alamofire.Method, URLString: URLStringConvertible, parameters: [String : AnyObject]?, encoding: ParameterEncoding, headers: [String : String]?) -> Alamofire.Result<String>? {
    var finishFlag = 0
    var AlamofireResult: Alamofire.Result<String>? = nil
    Alamofire.request(method, URLString, parameters: parameters, encoding: encoding, headers: headers)
        .responseString { (_, _, result) -> Void in
            if result.isSuccess {
                finishFlag = 1
                AlamofireResult = result
            }
            else {
                finishFlag = -1
            }
    }
    while finishFlag == 0 {
        NSRunLoop.currentRunLoop().runMode(NSDefaultRunLoopMode, beforeDate: NSDate.distantFuture())
    }
    return AlamofireResult
}


来源:https://stackoverflow.com/questions/27772010/how-to-have-a-completion-handler-block-after-alamofire-post-request

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!