How do I download and save a file locally on iOS using objective C?

bogdan picture bogdan · Mar 16, 2011 · Viewed 127.8k times · Source

I'm new to Objective-C and I want to download a file from the web (if it was changed on the webserver) and save it locally so it can be used by my application.

Mainly I want to implement what wget --timestamp <url> does.

Answer

Henning picture Henning · Mar 16, 2011

I'm not sure what wget is, but to get a file from the web and store it locally, you can use NSData:

NSString *stringURL = @"http://www.somewhere.com/thefile.png";
NSURL  *url = [NSURL URLWithString:stringURL];
NSData *urlData = [NSData dataWithContentsOfURL:url];
if ( urlData )
{
  NSArray       *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  NSString  *documentsDirectory = [paths objectAtIndex:0];  

  NSString  *filePath = [NSString stringWithFormat:@"%@/%@", documentsDirectory,@"filename.png"];
  [urlData writeToFile:filePath atomically:YES];
}