我刚开始使用 AFNetworking,到目前为止,它对于从网络获取数据来说效果很好。
但是现在我有一个需要下载到设备的文件列表
for(NSDictionary *issueDic in data)
{
Issue *issue = [[Issue alloc] init];
...
[self getOrDownloadCover:issue];
...
}
getOrDownloadCover:issue 检查文件是否已在本地存在,如果存在,则仅保存该路径,如果不存在,则从给定 url 下载文件
- (void)getOrDownloadCover:(Issue *)issue
{
NSLog(@"issue.thumb: %@", issue.thumb);
NSString *coverName = [issue.thumb lastPathComponent];
NSLog(@"coverName: %@", coverName);
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
__block NSString *filePath = [documentsDirectory stringByAppendingPathComponent:coverName];
if([[NSFileManager defaultManager] fileExistsAtPath:filePath])
{
// Cover already exists
issue.thumb_location = filePath;
NSLog(@"issue.thumb_location: %@", filePath);
}
else
{
NSLog(@"load thumb");
// Download the cover
NSURL *url = [NSURL URLWithString:issue.thumb];
AFHTTPClient *httpClient = [[[AFHTTPClient alloc] initWithBaseURL:url] autorelease];
NSMutableURLRequest *request = [httpClient requestWithMethod:@"GET" path:issue.thumb parameters:nil];
AFHTTPRequestOperation *operation = [[[AFHTTPRequestOperation alloc] initWithRequest:request] autorelease];
operation.outputStream = [NSOutputStream outputStreamToFileAtPath:filePath append:NO];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
issue.thumb_location = filePath;
NSLog(@"issue.thumb_location: %@", filePath);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"FAILED");
}];
[operation start];
}
}
getOrDownloadCover:issue 可以连续调用 20 次,所以我需要将所有请求放入队列中,一旦队列完成,它应该仍然能够保存路径(或者只是发送通知,因为我已经知道路径是什么)
对此有什么建议吗?