title: Downloading a file from url and saving to resources on iPhone
body: <p>Is it possible to download a file (i.e. an sqlite database file) from the Internet into your iPhone application programmatically for later use within the application?</p>
  
  <p>I am trying using <code>NSURLConnection</code>, but not able to save the file.</p>
  
  <p>Here is the example code I am trying:</p>
  
  <pre><code>- (void)viewDidLoad
  {
      [super viewDidLoad];
  
      NSString *file = [NSString stringWithFormat:@"http://en.wikipedia.org/wiki/Text_file"];
      NSURL *fileURL = [NSURL URLWithString:file];
  
      NSURLRequest *req = [NSURLRequest requestWithURL:fileURL];
      NSURLConnection *conn = [NSURLConnection connectionWithRequest:req delegate:self];  
  }
  
  - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
  {
      [self.fileData setLength:0];
      self.totalFileSize = [NSNumber numberWithLongLong:[response expectedContentLength]];
  }
  
  - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
  {
          [self.fileData appendData:data];        
  }
  
  - (void)connectionDidFinishLoading:(NSURLConnection *)connection
  {
      NSArray *dirArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,    NSUserDomainMask, YES);
      NSLog(@"%@", [dirArray objectAtIndex:0]);
  
      NSString *path = [NSString stringWithFormat:@"%@/blah.text", [dirArray objectAtIndex:0]];
  
      if ([self.fileData writeToFile:path options:NSAtomicWrite error:nil] == NO) {
          NSLog(@"writeToFile error");
      }
      else {
          NSLog(@"Written!");
      }
  }
  </code></pre>