as ASHTHTTP已被弃用,对于我正在努力学习AFNetworking的新项目,我正面临一些我无法解决的问题。 我需要从我的网站下载许多图像以在本地保存。不幸的是,这些图像不是服务器独立的服务器,而是整合到一个plist中,图像数据返回给我一些参数
提供图像的php代码是$plist = new CFPropertyList();
$plist->add($maindict = new CFdictionary());
$maindict->add('foldername',new CFString($fol_name));
$file_ext = ($fol_name == "iPhoneRetina") ? "@2x.png" : ".png";
$file_path = "1";
$imgfile = __DIR__.'/documents/'.$file_path.'/'.$fol_name.'/doc_'.$file_path.'_pagina_'.$page_nr.$file_ext;
$imgbinary = fread(fopen($imgfile, "r"), filesize($imgfile));
$maindict->add('image',new CFData($imgbinary));
$maindict->add('page_nr',new CFNumber($page_nr));
$maindict->add('document_id',new CFNumber($doc_id));
管理我已使用此代码的服务器页面的请求
AFHTTPClient *client = [[AFHTTPClient alloc] initWithBaseURL:downloadURL];
NSDictionary *params;
AFHTTPRequestOperation *operation;
for (int x = 0; x < 10; x++) {
params = @{
@"page_nr" : [NSNumber numberWithInt:x],
@"doc_id" : @1,
};
NSMutableURLRequest *request = [client requestWithMethod:@"POST" path:@"/getMagazinePage.php" parameters:params];
operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[tempOperations addObject:operation];
}
[client enqueueBatchOfHTTPRequestOperations:tempOperations
progressBlock:^(NSUInteger numberOfCompletedOperations, NSUInteger totalNumberOfOperations) {
dispatch_async(dispatch_get_main_queue(), ^{
[cell setDownloadProgress:(float)numberOfCompletedOperations/(float)totalNumberOfOperations];
});
} completionBlock:^(NSArray *operations) {
[cell setDownloaded:YES];
/* for (AFHTTPRequestOperation *ro in operations) {
if (ro.error) {
NSLog(@"++++++++++++++ Operation error");
}else {
//NSLog(@"Operation OK: %@", [ro.responseData description]);
}
}*/
}];
但是我无法在进度块中保存图像(因为我没有其他参数到块)并且通过操作数组迭代可能会消耗一点内存,以防图像真的很重或者那里有很多页面。 我读过有人建议使用
operation.outputStream = [NSOutputStream outputStreamToFileAtPath:@"download.zip" append:NO];
但在这种情况下,我没有直接的图像流,而是包含在plist中的值。 有没有人面临这个问题,如何解决它?
答案 0 :(得分:1)
您可以在每项操作上设置completionBlock
以执行您需要的任何操作,无论是在某处保存responseData
还是在您拥有的内容。
请注意,无法保证所有操作的完成块将在批处理完成时完成,因此不要依赖于批处理完成块中的完成块。
答案 1 :(得分:0)
// You need this line to download the file directly to the path above, as you pointed out
operation.outputStream = [NSOutputStream outputStreamToFileAtPath:filePath append:NO];
// Within the completion block, you can have some thing like
NSString *contentDisposition = [[operation.response allHeaderFields] objectForKey:@"Content-Disposition"];
and within contentDisposition string you will have the file name etc. That way, you will know the file name to save.