我正在使用Alamofire使用for-in
循环对数组中的每个项目发出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_create
和dispatch_group_notify
。有关实现的详细信息,请查看此线程。
来自链接线程的示例代码:
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)
})
})
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句