My app allows for downloading a PDF to the device. However, while the PDF is being downloaded, the app is unable to do anything until the download completes. How can I do this so other actions can be handled while download is in progress? This is what I have so far for downloading it.
RSSEntry *entry = [_allEntries objectAtIndex:indexPath.row];
NSString *urlString = entry.articlePDF;
NSURL *url = [NSURL URLWithString:urlString];
NSData *data = [NSData dataWithContentsOfURL:url];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *filename = [entry.articleTitle stringByAppendingString:@".pdf"];
NSString *removed = [filename stringByReplacingOccurrencesOfString:@"/" withString:@""];
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *pdfPath = [documentsDirectory stringByAppendingPathComponent: removed];
NSLog(@"Downloadstarted%@", pdfPath);
[data writeToFile:pdfPath atomically:YES];
You need to run it in a background thread, like that:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
RSSEntry *entry = [_allEntries objectAtIndex:indexPath.row];
NSString *urlString = entry.articlePDF;
NSURL *url = [NSURL URLWithString:urlString];
NSData *data = [NSData dataWithContentsOfURL:url];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *filename = [entry.articleTitle stringByAppendingString:@".pdf"];
NSString *removed = [filename stringByReplacingOccurrencesOfString:@"/" withString:@""];
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *pdfPath = [documentsDirectory stringByAppendingPathComponent: removed];
NSLog(@"Downloadstarted%@", pdfPath);
[data writeToFile:pdfPath atomically:YES];
})
Use ASIHTTPRequest for download
self.request = [ASIHTTPRequest requestWithURL:pdflinkURL];
[self.request setDidFinishSelector:@selector(requestedPDFFinished:)];
[self.request setDidFailSelector:@selector(requestedPDFFailed:)];
[self.request setShouldContinueWhenAppEntersBackground:YES];
self.request.delegate = self;
[self.request setDownloadProgressDelegate:self];
[self.request startAsynchronous];
- (void)requestedPDFFinished:(ASIHTTPRequest *)req
{
NSData *recievedData = [req responseData];
// Save top Document Directory
}
//sagar change
- (void)requestedPDFFailed:(ASIHTTPRequest *)req
{
NSLog(@"%@",req.error);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.