title: How to tell when file has finished downloading and ready to use?
body: <p>I am downloading a file (.json) from my own web service and whe it is finished downloading I need the contents to be 'unpacked' into a local SQLlite database.  </p>
  
  <p>I understannd that NSURLConnection downloads the file asynchronously on another thread to keep the main thread open.  The problem is that when the file download has started, the main thread, obviously, carries on doing what it's doing - in this case trying to load the contents of the file into the database.  By the time this happens the file either does not yet exist OR exists but is not yet complete.  </p>
  
  <p>How do I run the method that input the contents of the file into the database only AFTER the file is actually fully downloaded and ready to use?</p>
  
  <pre><code>-(void)downloadTheFileFrom:(NSString*)url withToken:(NSString*)token
  {   
      NSString *conURL = [NSString stringWithFormat:@"%@/%@", apiURL, url];
      NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:conURL]];
      [request setHTTPMethod:@"GET"];
  
      [request addValue:@"application/json" forHTTPHeaderField:(@"content-type")];
      [request addValue:token forHTTPHeaderField:(@"X-TOKEN")];
      NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:NO];
  
      [conn scheduleInRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
  
      [conn start];
      [self saveJsonToDatabase];
  } 
  </code></pre>
  
  <p>Method that saves the file to the database:</p>
  
  <pre><code>-(void)saveJsonToDatabase
  {
      NSString *jsonFileToSave = @"drug.json";
      NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
      NSError *jsonError = nil;
  
      NSString *jsonFile = [documentsPath stringByAppendingPathComponent:[NSString stringWithFormat:@"/content/formulary/files/%@", jsonFileToSave]];
      NSData *jsonData = [NSData dataWithContentsOfFile:jsonFile];
      NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&amp;jsonError];
  
      NSString *formularyTable = [NSString stringWithFormat:@"formulary_%@", [jsonFileToSave stringByDeletingPathExtension]];
  
      FormularyDBManager *formularyDBManagerInstance = [FormularyDBManager new];
      [formularyDBManagerInstance insertInto:formularyTable arrayOfDicts:jsonArray];
  }
  </code></pre>
  
  <p>Delegate methods for NSURLConnection:</p>
  
  <pre><code>-(void)connection:(NSURLConnection*)connection didReceiveResponse:(NSURLResponse *)response {
      [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
  
      NSString *apiUrl = [NSString stringWithFormat:@"%@",[response URL]];
      NSArray *pathComponents = [apiUrl pathComponents];
      NSString *areaFolder = [pathComponents objectAtIndex:3];
      NSString *fileName = [response suggestedFilename];
      NSString *fileType = [fileName pathExtension];
  
      NSString *docsfolderPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
      NSString *folderPath = [docsfolderPath stringByAppendingString:[NSString stringWithFormat:@"/content/%@/%@", areaFolder, contentType]];
  
      BOOL isDir;
      NSFileManager *fileManager= [NSFileManager defaultManager];
      if(![fileManager fileExistsAtPath:folderPath isDirectory:&amp;isDir])
          if(![fileManager createDirectoryAtPath:folderPath withIntermediateDirectories:YES attributes:nil error:NULL])
              NSLog(@"FileDownloader - connection - Error: Create folder failed %@", folderPath);
  
      NSString *filePath = [folderPath stringByAppendingPathComponent:fileName];
  
      [[NSFileManager defaultManager] createFileAtPath:filePath contents:nil attributes:nil];
      connection.file = [NSFileHandle fileHandleForUpdatingAtPath:filePath];
  
      _currentFile = fileName;
  }
  -(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
      [connection.file writeData:data];
  }
  -(NSCachedURLResponse *)connection:(FileURLConnection *)connection willCacheResponse:(NSCachedURLResponse*)cachedResponse {
      return nil;
  }
  -(void)connectionDidFinishLoading:(NSURLConnection *)connection 
  {
      [connection.file closeFile]; 
  }
  -(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
      NSLog(@"GetData - connection - error - %@", error);
  }
  </code></pre>