简体   繁体   English

如何在Alamofire Post请求后拥有一个完成处理程序/块?

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

I have a method which handles a Apple Push Notification Service remote notification. 我有一个处理Apple Push Notification Service远程通知的方法。 When this method is executed, I want it to call my server and do a HTTP POST request using the Alamofire library. 执行此方法时,我希望它调用我的服务器并使用Alamofire库执行HTTP POST请求。 I want to execute another method that will handle the response of the POST request. 我想执行另一个处理POST请求响应的方法。

The problem for me is that I am using an existing API to fetch a profile from the server in this POST request. 对我来说问题是我使用现有的API在此POST请求中从服务器获取配置文件。 So I need to use this existing API and figure out when this profile fetch is specifically triggered from the remote notification. 因此,我需要使用此现有API,并确定何时从远程通知中专门触发此配置文件提取。

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? 由于Alamofire请求是在后台队列中完成的,因此在从服务器接收到配置文件后,如何执行方法呢?

What would be a good option to solving this issue? 什么是解决这个问题的好方法?

Thank you! 谢谢!

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? 由于Alamofire请求是在后台队列中完成的,因此在从服务器接收到配置文件后,如何执行方法呢?

Response handling is built in to Alamofire. 响应处理内置于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; 注意.response方法调用,它向请求对象添加一个完成处理程序; the completion handler is invoked by Alamofire when the request completes (or fails). 当请求完成(或失败)时,Alamofire将调用完成处理程序。

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. 请注意传递给updateProfile方法的showAlert参数。 If you pass in true , it calls the showProfileWasUpdatedAlert method to show your alert after receiving the server's response. 如果传入true ,则会在收到服务器响应后调用showProfileWasUpdatedAlert方法显示警报。 Note that this boolean value is "captured" by the closure that handles the Alamofire response because the closure was defined inside the updateProfile function. 请注意,处理Alamofire响应的闭包“捕获”此布尔值,因为闭包是在updateProfile函数内定义的。

This, IMHO, is a better approach than declaring an app global inside your AppDelegate. 恕我直言,这比在AppDelegate中声明应用程序全局更好。

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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在同一函数中,如何仅对2个Alamofire请求使用1个完成处理程序 - How to have only 1 completion handler for 2 Alamofire request in the same function Alamofire请求不在NSOperation内运行完成块 - Alamofire request not running completion block inside NSOperation Alamofire不发出GET请求,而是通过Success调用完成处理程序 - Alamofire doesn't make GET Request but call completion handler with Success Alamofire网络获取的完成处理程序 - Completion handler for Alamofire network fetch 如何在@synchronized块中等待完成处理程序? - How to wait for completion handler inside a @synchronized block? 如何使用块完成处理程序实现类方法 - How to implement a class method with a block completion handler iOS facebook图形请求完成处理程序块未调用 - iOS facebook graph request completion handler block not called Alamofire请求最初返回值,但在通过完成处理程序传递时被接收为nil - Alamofire Request initially returns value but is received as nil when passed through completion handler 完成后台获取后,块完成处理程序引用为nil - Block completion handler reference is nil after completing background fetch Swift 2.0 Alamofire完成处理程序返回Json - Swift 2.0 Alamofire Completion Handler Return Json
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM