views:

36

answers:

2

How can I download a PDF document from the web to my apps Document folder?

I want to grab a version of a PDF from the web as an application is launched and use this in the app. It will need to be copied to the Apps Documents folder so it can be used from there until the app is launched again. Obviously I will need to check the date stamp on the doc to see if we need to update it. Maybe there's a way to check the PDF metadata for a version number?

+1  A: 

Look at the documentation for NSURLConnection

An NSURLConnection will allow you to make an HTTP request to a webserver and download the data.

You should implement the NSURLConnectionDelegate methods. One of the important ones is connection:didReceiveData: - here you should append the received data to an initialised NSMutableData object.

Eventually, after the download completes, you should get the connectionDidFinishLoading: callback, and from there you can save the downloaded data to the disk.

You can use the NSSearchPathForDirectoriesInDomains() function to get the path to the documents folder by passing the NSDocumentDirectory constant.

Finally, to save the data, you can use the writeToFile:atomically: method on NSData.

Jasarien
I'd like to be able to mark both answers as correct because they both are but I'm giving it to Tom cause it's plain old DIRTY! Thanks for your feedback. Appreciate it.
Lee Probert
+2  A: 

Quick and dirty -- no error checking and no nice callbacks that you would receive from using NSURLConnection and its delegate protocol (which may be nice if you want to be notified of errors, progress, etc.)

// fileURL is an NSURL that points to  your pdf file
NSData *fileData = [NSData dataWithContentsOfURL:fileURL];

NSArray *paths =  NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,  NSUserDomainMask, YES); 
NSString *localFilename = [(NSString *)[paths objectAtIndex:0] stringByAppendingPathComponent:@"myPDF"];

[fileData writeToFile:localFilename atomically:YES];
TomH
You win cause it's DIRTY!
Lee Probert
Dirty isn't a term I'd use in selecting the right way to do something. Either way, `dataWithContentsOfURL:` is a blocking API and will cause your UI to become non-responsive while the download is in progress (especially over an EDGE or 3G connection with a reasonably sized PDF). This can be grounds for rejection when submitting apps to the App Store.
Jasarien