我设置了一个循环,用于下载一系列图片,然后使用UIImageView
的animationImages
属性进行动画处理。我想知道何时循环内的所有块都执行完毕,以便开始进行动画处理,想知道如何确定它们何时完成执行?谢谢!
for (PFObject *pictureObject in objects){
PFFile *imageFile = [pictureObject objectForKey:@"image"];
NSURL *imageFileURL = [[NSURL alloc] initWithString:imageFile.url];
NSURLRequest *imageRequest = [NSURLRequest requestWithURL:imageFileURL];
[tokenImageView setImageWithURLRequest:imageRequest placeholderImage:nil success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {
[self.downloadedUIImages addObject:image]; //This is a mutableArray that will later be set to an UIImageView's animnationImages
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) {
NSLog(@"Error %@", error);
}];
}
//When I know all the blocks have finished downloading, I will then to animate the downloaded images.
编辑:遇到 Error -999
问题
当我执行提供的答案中的代码时,遇到了以下问题:Domain=NSURLErrorDomain Code=-999 "The operation couldn’t be completed. (NSURLErrorDomain error -999.)"
快速搜索显示,Error -999
的意思是“在上一个请求完成之前发出了另一个请求”,这在这里肯定是正确的,因为我正在快速连续地进行多个请求。推荐的修复方法在这里对我没有用,因为它只会成功下载一个UIImage(最后一个请求),以前的请求都会失败。我想知道这里或AFNetworking中是否有解决方法?谢谢!
编辑2:基于 @David 的解决方案的工作代码
for (PFObject *pictureObject in objects){
PFFile *imageFile = [pictureObject objectForKey:@"image"];
NSURL *imageFileURL = [[NSURL alloc] initWithString:imageFile.url];
NSURLRequest *imageRequest = [NSURLRequest requestWithURL:imageFileURL];
AFHTTPRequestOperation *requestOperation = [[AFHTTPRequestOperation alloc] initWithRequest:imageRequest];
requestOperation.responseSerializer = [AFImageResponseSerializer serializer];
dispatch_group_enter(group);
[requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"Response: %@", responseObject);
UIImage *retrivedImage = (UIImage *)responseObject;
[self.downloadedUIImages addObject:retrivedImage];
dispatch_group_leave(group);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Image error: %@", error);
dispatch_group_leave(group);
}];
[requestOperation start];
counter ++;
}
dispatch_group_notify(group, dispatch_get_main_queue(), ^{
NSLog(@"Horray everything has completed");
NSLog(@"What is here %@", self.downloadedUIImages);
NSLog(@"Done");
});