title: Downloading a file using NSURLConnection?
body: <p>I have an API that gets me the file URL to download. I am using <code>NSURLConnection</code> to download the file. The file size could be a little big because it's an MP4.</p>
  
  <h2>Code Steps:</h2>
  
  <ol>
  <li><p>Initialized <code>NSMutableURLRequest</code> and added <code>HttpHeaderField</code> to it with the byte index I want to resume download from. (I do this because internet connection could be lost).</p></li>
  <li><p>Initialized <code>NSURLConnection</code> with the <code>NSMutableURLRequest</code>.</p></li>
  <li><p>Used <code>connection:didReceiveData:</code> to receive data segments and append it to a global <code>NSMutableData</code> object.</p></li>
  <li><p>An error message could be generated because of an internet problem and it's handled using <code>connection:didFailWithError:</code>. In this handler I <code>setText</code> the download status label with the message "<em>No internet connectivity, or it is very slow</em>". Sleep for 1 second and then go back to step one again.</p></li>
  </ol>
  
  <h2>Code:</h2>
  
  <pre><code>- (void)viewDidLoad
  {
      [super viewDidLoad];
      [self resumeDownload];
  }
  
  - (void)resumeDownload
  {
      NSURL *url = [NSURL URLWithString:video-&gt;videoUrl];
      NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
      if (receivedData==nil)
      {
          receivedData = [[NSMutableData alloc] init];
      }
      else
      {
          NSString *range = [NSString stringWithFormat:@"bytes=%i-", receivedData.length];
          [request setValue:range forHTTPHeaderField:@"Range"];
      }
  
      downloadConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
  }
  
  - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
  {
      NSLog(@"%@", [response description]);
  }
  
  - (void) connection:(NSURLConnection*)connection didFailWithError:(NSError*) error
  {
      NSLog(@"Download Fail : %d", [error code]);
      [status setText:@"No internet conectivity or it is very slow."];
      sleep(1);
      [self resumeDownload];
  }
  
  - (void) connectionDidFinishLoading:(NSURLConnection*)connection
  {
      // save the file
  }
  
  - (void) connection: (NSURLConnection*) connection didReceiveData: (NSData*) data
  {
      if(connection == downloadConnection)
      {
          [receivedData appendData:data];
          [status setText:[NSString stringWithFormat:@"Downloading: %d Bytes.", receivedData.length]];
      }
  }
  </code></pre>
  
  <h2>Screen Shots:</h2>
  
  <p><img src="https://i.stack.imgur.com/HdnQO.png" alt="enter image description here">
  <img src="https://i.stack.imgur.com/KF4zb.png" alt="enter image description here"></p>
  
  <p>Note: When the internet reconnects, the download will resume automatically.</p>
  
  <p>Is this a proper solution for the problem?</p>