afnetworking:在队列中下载文件
-
11-12-2019 - |
题
我刚刚开始使用afnetworking,到目前为止它刚刚从网络上获取数据。
但现在我有一个需要下载到设备的文件列表
for(NSDictionary *issueDic in data)
{
Issue *issue = [[Issue alloc] init];
...
[self getOrDownloadCover:issue];
...
}
.
getOrdownloadCover:问题检查文件是否已在本地存在,如果它,它只需保存该路径,如果没有,它会从给定的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:问题可以连续调用20次,所以我需要将所有请求放入队列中,并且一旦队列完成,它仍然可以保存路径(或者只是发送出来通知,因为我已经知道路径是什么)
这个问题?
解决方案
添加一个 NSOperationQueue
对于一个对象,您可以在应用程序中的任何点处获取实例,例如在您的AppDelegate中。然后只需将AFHTTPRequestOperation
添加到此队列(如:只需处理完成块中的保存,要么从主线程上调用methode,或者在主线程上或发布 NSNotification
其他提示
不确定这是否有用,但...
而不是使用自己的操作Queue,您可以使用AFHTTPClient的操作。用enqueuehttpoperation征收单一操作或用enqueuebatcherations延长一系列操作(我回忆起这些方法名称从内存中,可能会关闭一点)。
就存储了每个操作的数据,您可以子类化AFHTTPREQUESTOPERATION并为您要存储的路径设置属性。这样的东西。
不隶属于 StackOverflow