用法解析:
比如我现在要到服务端请求十几个pdf文件,下载到本地Document目录,那么用这个就非常好,
好处一:不会卡死主线程
好处二:下载完成有回调,可以在下载完成后,做一些刷新UI的操作,爽歪歪。
实例操作:
-(void)downloadPdfFileWithUrl:(NSArray *)modelList{
if(self.config.hasUpdateData)return;
NSMutableArray *mutableOperations = [NSMutableArray array];
int countIndex = 0;
for (MMPGetManualElementManualList *Model in modelList)
{
NSString *fileName = Model.manualName;
[[NSUserDefaults standardUserDefaults] setValue:fileName forKey:[NSString stringWithFormat:@"%@%d",fileNameKey,countIndex]];
NSString *pdf_diret = Model.annexPath;
NSString *fileContentPath = [self getManualPath];
NSString *pdf_loc_path = pdf_diret.lastPathComponent;
NSString *pdf_url_path = [NSString stringWithFormat:@"%@/%@",baseURL,pdf_diret];
NSString *abusolutePath = [fileContentPath stringByAppendingPathComponent:pdf_loc_path];
[pdf_path_array addObject:pdf_loc_path];
countIndex++;
BOOL existFile = [[NSFileManager defaultManager] fileExistsAtPath:abusolutePath isDirectory:NO];
if (existFile && [self fileSizeAtPath:abusolutePath] == 0) {
[self removeFileAtPath:abusolutePath];
}else if(existFile){
continue;
}
NSURLRequest* request = [NSURLRequest requestWithURL:[NSURL URLWithString:[pdf_url_path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding] ] cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:60.f];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setOutputStream: [NSOutputStream outputStreamToFileAtPath:abusolutePath append:NO]];
[mutableOperations addObject:operation];
}
__block CGFloat progress = 0.0f;
NSArray *operations = [AFURLConnectionOperation batchOfRequestOperations:mutableOperations progressBlock:^(NSUInteger numberOfFinishedOperations, NSUInteger totalNumberOfOperations) {
progress = (float)numberOfFinishedOperations/totalNumberOfOperations;
NSLog(@"%f complete", progress);
} completionBlock:^(NSArray *operations) {
NSLog(@"All operations in batch complete");
MMActivityIndicator_stop();
self.service.customLoadingHint = NO;
self.config.hasUpdateData = YES;
}];
[[NSOperationQueue mainQueue] addOperations:operations waitUntilFinished:NO];
}