Reputation: 10839
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?
Upvotes: 1
Views: 504
Reputation: 2990
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];
Upvotes: 3
Reputation: 58448
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
.
Upvotes: 2