我有一个从JSON API响应中解析的对象。此对象具有指向缩略图的链接。我有一个包含多个对象的数组,我想下载缩略图。所以我有一个循环开始为每个缩略图链接启动一个异步调用。
所以我在ViewController中有这个对象,我开始下载所有图像,如何检测所有调用何时完成?
这是我的代码:
public class NewsListItem: NSObject {
public var entries: [NewsListEntry]? = []
public func downloadThumbnails() {
for itm in entries! {
if(itm.thumbnail != "") {
itm.downloadThumbnail()
}
}
}
}
public class NewsListEntry: NSObject {
public var thumbnail: String = ""
public var thumbnailImage: UIImage = UIImage()
public func downloadThumbnail() {
GetImageHandeler().getImage(self.thumbnail, completionHandler: { (responseObject, error) in
self.thumbnailImage = responseObject!
})
}
}
答案 0 :(得分:3)
您可以使用dispatch_groups。在obj C中它看起来像这样:
dispatch_group_t serviceGroup = dispatch_group_create();
for (itm in entries){
dispatch_group_enter(serviceGroup);
[ImageHandler getImage:^(ConfigResponse *results, NSError* error){
// Do something with the error or results
dispatch_group_leave(serviceGroup);
}];
}
dispatch_group_notify(serviceGroup,dispatch_get_main_queue(),^{
// Do your stuff, everything has finished
});
您可以找到更详细的示例here