arrays - 仅在发出多个请求后调用函数

标签 arrays swift asynchronous alamofire for-in-loop

我正在使用 for-in 循环为数组中的每一项使用 Alamofire 发出 HTTP 请求。我想在收到所有回复后调用一个函数:

for product in products {
    let requestURL = "http://api.com/" + product
    let parameters = ["apiKey" : "myApiKey"]
    Alamofire.request(.GET, requestURL, parameters: parameters)                  
        .responseJSON { response in
             // do stuff here
        }
}

为了在完成时调用一个函数,我想我可以检查 product 是否是数组的最后一个元素,然后如果是这样就调用该函数(因为请求是异步的).我该怎么做?

最佳答案

您应该使用 GCD 在所有请求完成时得到通知。使用 dispatch_group_createdispatch_group_notify。有关实现细节,请查看此 thread .

来自链接线程的示例代码:

func downloadAllData(allDataDownloadedCompletionHandler:()->Void) {
    let dispatchGroup: dispatch_group_t = dispatch_group_create()
    let types = ["one", "two", "three"]  // there are actually about 10 requests called, but to make it simple I set it to 3
    for type in types {
        // enter group and run request
        dispatch_group_enter(dispatchGroup)
        self.downloadDataForType(type, group: dispatchGroup)
    }

    dispatch_group_notify(dispatchGroup, dispatch_get_main_queue(), {
        allDataDownloadedCompletionHandler()
    });
}

func downloadDataForType(type:String, group: dispatch_group_t) {
    Alamofire.request(Router.TypeData(type: type)).response({ (request, response, xmlResponse, error) -> Void in
        // request finished
        println("Data for type \(type) downloaded")

        // let's parse response in different queue, because we don't want to hold main UI queue 
        var db_queue = dispatch_queue_create("db_queue", nil)
            dispatch_async(db_queue, {
            if response?.statusCode == 200 {
               saveToDatabase(xmlResponse)
           }

            // leave group
            dispatch_group_leave(group)
        })
    })
}

关于arrays - 仅在发出多个请求后调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35661005/

相关文章:

php - 使用 jQuery/JS 读取 JSON 数组

c - a、&a、*a、a[0]、&a[0] 和 &a[0][0] 是相同的指针吗?

json - 无需 future/async 同步解析本地 json 文件

Java异步订单

node.js - 异步等待条件满足

arrays - 如何丢弃用户输入中除 a-z && A-Z && 0-9 之外的所有字符以查找可能的回文

python - 在 Python 中将数组保存到光栅文件的最简单方法

ios 视觉效果在进程发生时不更新。 ( swift 3)

swift - NSTextField 上的奇怪滚动

swift - 框架内的自定义控件在 Xcode 中不可配置或不可见