在iOS App中下载PDF冻结

时间:2013-06-27 05:17:58

标签: ios pdf nsurlconnection

我的应用允许将PDF下载到设备。但是,在下载PDF时,应用程序在下载完成之前无法执行任何操作。我该怎么做才能在下载过程中处理其他操作?这是我到目前为止下载它。

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];

2 个答案:

答案 0 :(得分:0)

你需要在后台线程中运行它,如:

    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];
    })

答案 1 :(得分:-1)

使用ASIHTTPRequest下载

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);
}