How to download PDF and store it locally on iPhone?

Zac Altman picture Zac Altman · Feb 9, 2010 · Viewed 51k times · Source

I am able to successfully view a PDF from a website. I want to be able to download that PDF to the device, then access that file locally.

When the app is opened, it will check the online PDF's date. If it is newer than the locally-stored PDF, the app will download the new one, otherwise it opens the locally-stored PDF.

The code I am currently using:

PDFAddress = [NSURL URLWithString:@"http://www.msy.com.au/Parts/PARTS.pdf"];
request = [NSURLRequest requestWithURL:PDFAddress];
[webView loadRequest:request];
webView.scalesPageToFit = YES;

How am I able to achieve this?

Answer

RVN picture RVN · Feb 13, 2010

I have found one method which I tried myself:

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

This will store your PDF locally and load it into your UIWebView.