Swift Alamofire如何处理来自循环的所有请求

时间:2017-02-07 15:18:11

标签: swift alamofire

我需要执行10个Alamofire请求的循环。当所有10个请求完成后如何处理?

3 个答案:

答案 0 :(得分:1)

创建一个包装类来发送网络请求。例如

TPushEvents

现在将其用作

class HttpRequest {
    static var requestCount:Int = 0

    class func sendRequest(onCompletion:(Bool)->()) {
        // Send alamofire request here 
        // below code is just a sample 
        Alamofire.request(...).validate().response(..completionHandler..) {

        // Check response & increment request count
        requestCount += 1

       if requestCount == 10 {
           // calling completion handler here
           onCompletion(true)
        }
     }
   }   
}

PS:上面提供的代码只是一个原型。实际语法可能不同

答案 1 :(得分:0)

在promises(第三方)或Operations(第一方)中包装请求将允许您对请求和代码执行一些依赖性管理,以便在它们全部完成时执行。

对于快速而肮脏的修复,您可以使用调度组。

let dispatchGroup = DispatchGroup()
var responses = [DataResponse<String>]()

dispatchGroup.enter()
Alamofire.request("https://www.google.com").responseString { response in
    DispatchQueue.main.async {
        responses.append(response)
        dispatchGroup.leave()
    }
}

dispatchGroup.enter()
Alamofire.request("https://www.yahoo.com").responseString { response in
    DispatchQueue.main.async {
        responses.append(response)
        dispatchGroup.leave()
    }
}

dispatchGroup.enter()
Alamofire.request("https://www.bing.com").responseString { response in
    DispatchQueue.main.async {
        responses.append(response)
        dispatchGroup.leave()
    }
}

dispatchGroup.notify(queue: DispatchQueue.main) { 
    print("Got \(responses.count) responses")
}

答案 2 :(得分:0)

使用DispatchGroups实现此目的的最佳方式

var myGroup = DispatchGroup()

 firstAlamofireRequest(){
  myGroup.enter()
}

 SecondAlamofireRequest(){
  myGroup.enter()
}

onFirstAlmoFireResponse(){
 myGroup.leave()
}

onSecondAlmoFireResponse(){
 myGroup.leave()
}

当groupDespatcher完成全部

这个方法将被称为

 myGroup.notify(qos: DispatchQoS.background, flags: DispatchWorkItemFlags.assignCurrentContext, queue: DispatchQueue.main) {
           // what to do after all requests are done 

        }