我正在构建一个iOS应用程序,它将下载300个pdf文件,每个文件大小大小为3mb。
我遇到了一个非常好的教程,其中包含一个代码示例:Link 代码示例:LINK
问题是,当运行此代码添加所有300个任务时,应用程序将冻结一段时间:
-(void)startAllDownloads{
for (int i=0; i<[self.arrFileDownloadData count]; i++) {
FileDownloadInfo *fdi = [self.arrFileDownloadData objectAtIndex:i];
// Check if a file is already being downloaded or not.
if (!fdi.isDownloading) {
// Check if should create a new download task using a URL, or using resume data.
if (fdi.taskIdentifier == -1) {
//new NSURLSessionDownloadTask
fdi.downloadTask = [self.session downloadTaskWithURL:[NSURL URLWithString:fdi.downloadSource]];
}
else{
fdi.downloadTask = [self.session downloadTaskWithResumeData:fdi.taskResumeData];
}
// Keep the new taskIdentifier.
fdi.taskIdentifier = fdi.downloadTask.taskIdentifier;
NSLog(@"starting download id:%lu",fdi.taskIdentifier);
// Start the download.
//dispatch_async(dispatch_get_main_queue(), ^{
[fdi.downloadTask resume];
//});
// Indicate for each file that is being downloaded.
fdi.isDownloading = YES;
}
}
}
我尝试过dispatch_queue但没有成功,它总是冻结。
提前致谢。
答案 0 :(得分:0)
尝试执行以下操作:
您将使用Grand dispatch并将优先级设置为high。这将允许您在后台下载内容时运行应用程序。
在viewDidLoad
方法中添加以下代码行
{dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{ //1
// DO ALL YOUR CODING HERE
dispatch_async(dispatch_get_main_queue(), ^{ // 2
});
//3
});
和解释
1我们设置了后台任务。在您的情况下异步下载pdf文件。 2我们在主队列上做了一些事情,例如更新UI以在下载后显示PDF。 3我们关闭括号和整个方法
希望有所帮助。此致!
编辑:那是一种下载PDF&#39;
的方式// Get the PDF Data from the url in a NSData Object
NSData *pdfData = [[NSData alloc] initWithContentsOfURL:[
NSURL URLWithString:@"http://www.example.com/info.pdf"]];
// Store the Data locally as PDF File
NSString *resourceDocPath = [[NSString alloc] initWithString:[
[[[NSBundle mainBundle] resourcePath] stringByDeletingLastPathComponent]
stringByAppendingPathComponent:@"Documents"
]];
NSString *filePath = [resourceDocPath
stringByAppendingPathComponent:@"myPDF.pdf"];
[pdfData writeToFile:filePath atomically:YES];
// Now create Request for the file that was saved in your documents folder
NSURL *url = [NSURL fileURLWithPath:filePath];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
[webView setUserInteractionEnabled:YES];
[webView setDelegate:self];
[webView loadRequest:requestObj];
答案 1 :(得分:0)
我是这样做的:
#define __ASYNC_BLOCK(code) dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), code)
#define __UI_THREAD_TASK(code) dispatch_async(dispatch_get_main_queue(), code);
然后在代码中的某个位置可以像这样使用:
...
__ASYNC_BLOCK(^{
// do download...
__UI_THREAD_TASK(^{
// update ui
})
});
...
编辑:查看跟踪进度部分Background Transfer Service in iOS 7 SDK。
接下来,因为下载任务在后台线程中工作,所以任何可视升级都必须在应用程序的主线程中进行。所以,在主队列操作的addOperationWithBlock:方法的块内部