我有一个应用程序,我必须下载大量文件,从400到900个文件,总共约1GB。
实现这一目标的最佳方法是什么?
NSURLSession
并且所有任务都加入其中? NSURLSession
并按包排队任务(例如10乘10)? NSURLSession
有不同的队列?实际上我在所有任务中都有一个NSURLSession
(每个文件一个)排队,但有时我得到一个Lost connection to background transfer service
。
这是我的代码:
if([[UIDevice currentDevice] isMultitaskingSupported])
{
__block UIBackgroundTaskIdentifier bgTask;
UIApplication *application = [UIApplication sharedApplication];
bgTask = [application beginBackgroundTaskWithExpirationHandler:^{
[application endBackgroundTask:bgTask];
bgTask = UIBackgroundTaskInvalid;
}];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSString *uuidString;
CFUUIDRef uuid = CFUUIDCreate(nil);
uuidString = CFBridgingRelease(CFUUIDCreateString(nil, uuid));
CFRelease(uuid);
// }
NSURLSessionConfiguration *sessionConfiguration;
if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"8.0"))
{
sessionConfiguration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:@"com.fiveflamesmobile.bakgroundDownload"];
}
else
{
sessionConfiguration = [NSURLSessionConfiguration backgroundSessionConfiguration:@"com.fiveflamesmobile.bakgroundDownload"];
}
sessionConfiguration.HTTPMaximumConnectionsPerHost = 5;
sessionConfiguration.sessionSendsLaunchEvents = YES;
sessionConfiguration.discretionary = YES;
sessionConfiguration.timeoutIntervalForResource = 0; //NO timeout
sessionConfiguration.timeoutIntervalForRequest = 0; //No timeout
sessionConfiguration.networkServiceType = NSURLNetworkServiceTypeBackground;
self.session = [NSURLSession sessionWithConfiguration:sessionConfiguration
delegate:self
delegateQueue:nil];
NSLog(@"##### ------- Sesion created succesfully");
// [self batchDownloading];
for (id<FFDownloadFileProtocol> file in self.selectedCatalogProducto.downloadInfo.arrayFiles)
{
[self startDownloadFile:file];
}
NSLog(@"##### ------- Download tasks created successfully ------");
[application endBackgroundTask:bgTask];
bgTask = UIBackgroundTaskInvalid;
});
}
}
答案 0 :(得分:1)
一个NSURLSession - 因为你只想处理一次基于会话的事情(例如auth)。
一个NSOperationQueue - 同时运行多个操作。 (见属性operationCount)。第一次实施NSOperation可能有点棘手,但我相信这将是你最好的选择。 https://developer.apple.com/library/mac/documentation/Cocoa/Reference/NSOperationQueue_class/index.html
http://nshipster.com/nsoperation/
哦,顺便说一句,这是一种高度面向对象的方法,总是很好看=)