首页 > 代码库 > iOS GCD结合AFNetworking异步下载
iOS GCD结合AFNetworking异步下载
- (void)downloadImages {
NSString *fileDir = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject;
// stringByAppendingPathComponent:@"image"];
dispatch_queue_t globalQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
_imgGroup = dispatch_group_create();
NSLog(@"start downloading");
dispatch_group_async(_imgGroup, globalQueue, ^{
dispatch_group_enter(_imgGroup);
NSString *filePath = [fileDir stringByAppendingPathComponent:@"image0.jpg"];
[self downloadImageToPath:filePath url:self.imgURLs[0]];
});
dispatch_group_async(_imgGroup, globalQueue, ^{
dispatch_group_enter(_imgGroup);
NSString *filePath = [fileDir stringByAppendingPathComponent:@"image1.jpg"];
[self downloadImageToPath:filePath url:self.imgURLs[1]];
});
dispatch_group_async(_imgGroup, globalQueue, ^{
dispatch_group_enter(_imgGroup);
NSString *filePath = [fileDir stringByAppendingPathComponent:@"image2.jpg"];
[self downloadImageToPath:filePath url:self.imgURLs[2]];
});
dispatch_group_notify(_imgGroup, globalQueue, ^{
NSLog(@"finish download");
});
}
- (void)downloadImageToPath:(NSString *)filePath url:(NSString *)url{
AFURLSessionManager *sessionMgr = [[AFURLSessionManager alloc] initWithSessionConfiguration:self.sessionConfig];
NSURL *imgURL = [NSURL URLWithString:url];
NSURLRequest *request = [NSURLRequest requestWithURL:imgURL];
NSURLSessionDownloadTask *downloadTask =
[sessionMgr downloadTaskWithRequest:request
progress:nil
destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
NSURL *documentURL = [NSURL fileURLWithPath:filePath];
return documentURL;
} completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
dispatch_group_leave(_imgGroup);
}];
[downloadTask resume];
}
iOS GCD结合AFNetworking异步下载