Failed to download and open a PDF file with error failed to find PDF header in ios

前端 未结 2 909
迷失自我
迷失自我 2020-12-18 15:30

I am having an app in which I am opening a PDF file from a url.

I am successfully able to open it in a webView.

Now I want to download that PDF file and sa

2条回答
  •  抹茶落季
    2020-12-18 16:11

    try this code for downloading & saving your pdf file

        UIActivityIndicatorView *indicator=[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    
       [indicator startAnimating];
    
        NSLog(@"Downloading Started");
        NSString *urlToDownload = @"http://gradcollege.okstate.edu/sites/default/files/PDF_linking.pdf";
        NSURL  *url = [NSURL URLWithString:urlToDownload];
        NSURLRequest *request=[[NSURLRequest alloc] initWithURL:url cachePolicy:NSURLCacheStorageAllowed timeoutInterval:120.0f];
    
        [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
    
            [indicator stopAnimating];
    
            if (!connectionError) {
    
                if ( data )
                {
                    NSArray   *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
                    NSString  *documentsDirectory = [paths objectAtIndex:0];
    
                    NSString  *filePath = [NSString stringWithFormat:@"%@/%@", documentsDirectory,@"myfile.pdf"];
    
                    //saving is done on main thread
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [data
                         writeToFile:filePath atomically:YES];
                        NSLog(@"File Saved !");
    
                        NSURL *url = [NSURL fileURLWithPath:filePath];
                        NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
                        [_rssWebView setUserInteractionEnabled:YES];
                        //[_rssWebView setDelegate:self];
                        [_rssWebView loadRequest:requestObj];
                    });
                }
            }
    
        }];
    

提交回复
热议问题