【发布时间】:2015-03-08 21:15:35
【问题描述】:
想法
我正在使用 AFNetworking 构建文件下载管理器,并且正在使用 AFURLSessionManager 类。该应用程序假设从服务器下载 mp3 文件。
我担心内存消耗,所以我试图将同时下载的数量限制为 1。
我知道 AFURLSessionManager 中有一个名为 operationQueue 的 NSOperationQueue 属性,默认情况下它一次限制为 1 个操作。所以我将我的 NSURLSessionDownloadTask 添加到 operationQueue。
问题
代码不工作。文件是同时下载的,而不是一个接一个。
代码
// 1. build sessionManager and prepare some vars
// note: by testing i found that it's better to init NSURLSessionConfiguration with backgroundSessionConfigurationWithIdentifier for memory issues
NSURLSessionConfiguration *conf = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:@"special_Identifier"];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:conf];
NSURL *urlDocs = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory
inDomain:NSUserDomainMask
appropriateForURL:nil
create:NO
error:nil];
__block NSProgress *progress = Nil;
// 2. open sessionManager operation Queue and add this new download
[manager.operationQueue addOperationWithBlock:^{
// 2.1 init new download request
NSURLRequest *request = [[NSURLRequest alloc]initWithURL:[NSURL URLWithString:fileLink]];
// 2.2 creat a NSURLSessionDownloadTask
NSURLSessionDownloadTask *downloadTask = [self.downloadManager downloadTaskWithRequest:request progress:&progress
destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
return [urlDocs URLByAppendingPathComponent:fileName];
} completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
if (!error) {
NSLog(@"done: %@", filePath);
}else{
NSLog(@"error %@",error);
}
}];
// 2.3 start downloading
[downloadTask resume];
// 2.4 track downloading progress using KVO
[progress addObserver:self
forKeyPath:NSStringFromSelector(@selector(fractionCompleted))
options:NSKeyValueObservingOptionNew
context:(__bridge void *)(fileLink)];
}];
【问题讨论】:
标签: ios objective-c afnetworking-2 download