2015-03-08 22 views
1

理念限制AFURLSessionManager

我使用AFNetworking建立档案的下载管理器,我使用AFURLSessionManager类并发下载的数量。该应用程序假设从服务器下载mp3文件。

我担心内存消耗,所以我试图同时下载的数量限制为1

我知道有在AFURLSessionManager一个NSOperationQueue属性调用operationQueue和它仅限于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

在AFNetworking 2(和AFNetworking 3),你可以初始化你的AFHTTPSessionManagerNSURLSessionConfiguration(使用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]; 

文档: