title: Continuing an already started HTTP call in background in iOS
body: <p>I perform a synchronous HTTP request to a REST service regularly to get possible data updates for my app. I do the call when the app is active and a timer is finished, this is the code snippet:</p>
  
  <pre><code>__block BOOL result;
  
              dispatch_queue_t queue = dispatch_queue_create(UpdateQueue, NULL);
              dispatch_async(queue,^{
  
                  UpdateMngr *updateMngr = [[UpdateMngr alloc] init];
                  result = [updateMngr getUpdatedData];
  
                  dispatch_async(dispatch_get_main_queue(), ^{
                      if (result) {
                          // Notify user update is OK
                      }
                      else {
                          // Notify user update failed
                      }
                  });
              });
  </code></pre>
  
  <p>Where the <code>getUpdatedData</code> method is:</p>
  
  <pre><code>- (BOOL)getUpdatedData
  {
  NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:self.serviceURL cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];
  [request setHTTPMethod:@"POST"];
  [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
  
  NSURLResponse *response = nil;
  NSError *error = nil;
  
  NSData* jsonData = [self getRequestBody];    
  [request setHTTPBody:jsonData];
  NSData *content = [NSURLConnection sendSynchronousRequest:request
                                          returningResponse:&amp;response
                                                      error:&amp;error];
  
  if (([content length] &gt; 0) &amp;&amp; (error == nil)) {
      id parseResult = [self parseJson:content];
  
      if ([parseResult isKindOfClass:[NSString class]]) {
          return NO;
      }
      else if ([parseResult isKindOfClass:[NSDictionary class]]) {
              @try {
                      // Success
                      // Save data in database
              }
              @catch (NSException *ex) {
                      // Handle error
              }
      }
  }
  else if (([content length] == 0) &amp;&amp; (error == nil)) {
      // No updated data
      return NO;
  }
  else if (error != nil) {
      return NO;
  }
  
  return YES;
  }
  </code></pre>
  
  <p>It seems that going to background or going to inactive state because, for example, an incoming phone call, the request is interrupted and I see that sometimes the app behaves as if the data I expect to receive from the service is not complete and only a piece of it is shown to the user, despite I've received the response.</p>
  
  <p>I've been reading the <a href="https://developer.apple.com/library/ios/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/BackgroundExecution/BackgroundExecution.html#//apple_ref/doc/uid/TP40007072-CH4-SW3" rel="nofollow">iOS App Programming Guide</a> section about executing finite-length tasks in background, but I'm not sure how to apply it here, since the code snippet in that document seems to launch the complete task in background, while what I need is to finish an already started task... Should I always perform my task in background, just in case? Or how could I handle this scenario? I guess this should be a quite common scenario, but I don´t find any example or tutorial that enlightens me.</p>
  
  <p>Note: my app works for <strong>iOS 5+</strong></p>
  
  <p>Thanks in advance</p>
  
  <p><strong>EDIT:</strong> Would this be the appropriate solution?:</p>
  
  <pre><code>- (void)getUpdates
  {
     self.bgTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
                  // Clean up any unfinished task business by marking where you.
                  // stopped or ending the task outright.
                  [[UIApplication sharedApplication] endBackgroundTask:self.bgTask];
                  self.bgTask = UIBackgroundTaskInvalid;
              }];
  
     __block BOOL result;
  
              dispatch_queue_t queue = dispatch_queue_create(UpdateQueue, NULL);
              dispatch_async(queue,^{
  
                  UpdateMngr *updateMngr = [[UpdateMngr alloc] init];
                  result = [updateMngr getUpdatedData];
  
                  dispatch_async(dispatch_get_main_queue(), ^{
                      if (result) {
                          // Notify user update is OK
                      }
                      else {
                          // Notify user update failed
                      }
                  });
              });
  
     // Finish background task
              if (self.bgTask != UIBackgroundTaskInvalid) {
                  [[UIApplication sharedApplication] endBackgroundTask:self.bgTask];
                  self.bgTask = UIBackgroundTaskInvalid;
              }
  }
  </code></pre>
  
  <p>Where <code>self.bgTask</code> is <code>@property UIBackgroundTaskIdentifier bgTask;</code></p>