观
我正在使用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)];
}];
答案 0 :(得分:0)
在AFNetworking 2(和AFNetworking 3)中,您可以使用AFHTTPSessionManager
(使用NSURLSessionConfiguration
)初始化AFHTTPSessionManager initWithBaseURL:sessionConfiguration:
。在那里,您可以指定每个主机的连接数(HTTPMaximumConnectionsPerHost
)。
样品:
NSURL *url = [NSURL URLWithString:@"myurl.net"];
NSURLSessionConfiguration *configuration = NSURLSessionConfiguration.defaultSessionConfiguration;
configuration.HTTPMaximumConnectionsPerHost = 1;
AFHTTPSessionManager *sessionManager = [[AFHTTPSessionManager alloc] initWithBaseURL:url sessionConfiguration:sessionConfiguration];
文档: