AFNetworking/NSURLSession需要很长时间来创建超过100个任务来下载文件
我的应用程序需要下载许多文件,我使用for循环来创建下载任务。以下方法是AFNetworking提供的方法。AFNetworking/NSURLSession需要很长时间来创建超过100个任务来下载文件
- (NSURLSessionDownloadTask *)downloadTaskWithRequest:(NSURLRequest *)request
progress:(void (^)(NSProgress *downloadProgress)) downloadProgressBlock
destination:(NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination
completionHandler:(void (^)(NSURLResponse *response, NSURL *filePath, NSError *error))completionHandler{
__block NSURLSessionDownloadTask *downloadTask = nil;
url_session_manager_create_task_safely(^{
downloadTask = [self.session downloadTaskWithRequest:request];
});
[self addDelegateForDownloadTask:downloadTask progress:downloadProgressBlock destination:destination completionHandler:completionHandler];
return downloadTask;
}
我的代码是这样的:
for (NSInteger i = 0; i<= 500; i++) {
NSMutableURLRequest *request = array[i];
NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:downloadProgress destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
return destinationPath;
} completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
completionBlock(filePath,error);
}];
[downloadTask resume];
}
问题是
downloadTask = [self.session downloadTaskWithRequest:request];
此行花费比较长的时间完成,这意味着如果EXCUTE它500次,需要5〜6秒。
我的应用程序弹出一个alertView来询问用户是否下载,如果他们点击Yes,它会执行类似for循环的操作,结果UI将卡住5到6秒直到所有任务都完成创建。
我不确定我是否正确或是否有其他方法可以批量下载。 任何人都可以帮助我吗?谢谢。
你应该在不同的线程下运行(在后台运行)。这样,用户将继续顺利使用该应用程序。尝试下面的代码:
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { // in half a second...
//do your download here
}
希望这有助于!
我建议你过渡到AFHTTPSessionManager
,它使用NSURLSession
。旧的AFHTTPRequestOperationManager
基于NSURLConnection
,但现在不推荐使用NSURLConnection
。事实上,AFNetworking 3.0已完全退役AFHTTPRequestOperationManager
。
所以,AFHTTPSessionManager
下载方法可能是:
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
for (NSInteger i = 0; i < urlArray.count; i++) {
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlArray[i]]];
NSURLSessionTask *task = [manager downloadTaskWithRequest:request progress:^(NSProgress *downloadProgress) {
[self.delegate downloadProgression:downloadProgress.fractionCompleted * 100.0];
} destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
return [NSURL fileURLWithPath:[self.documentDirectory getDownloadContentPath:contentPaths[i]]];
} completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
NSLog(@"File downloaded to: %@", filePath);
NSLog(@"Error: %@" error.localizedDescription);
}];
[task resume];
}
这正是我现在使用的。问题是NSURLSessionTask * task = [manager downloadTaskWithRequest:请求这需要很长时间来创建任务,并且如果循环非常大,比如说500次,这将会很长。 – user2053760
我可以使用GCD做这件事? – user2053760
cgd是什么意思? –