title: How to keep iphone ios websocket connection alive while in the background?
body: <p>I created a chat application using SocketRocket,when I quit the app(enter background mode) I want to receive the chat message! so i could do that by calling it a VoIP app but some people says Apple will reject it from the App Store unless it also truly does VoIP. So how can I do that and if the only way to do that is by calling it a VoIP app how does whatsapp handles this situation??</p>
  
  <p>Here's what i did to keep the app alive in the background:</p>
  
  <pre><code>- (void)applicationDidEnterBackground:(UIApplication *)application
  {
  
  
   NSLog(@"Application entered background state.");
      NSAssert(self.backgroundTask == UIBackgroundTaskInvalid, nil);
      self.didShowDisconnectionWarning = NO;
  
  self.backgroundTask = [application beginBackgroundTaskWithExpirationHandler: ^{
      dispatch_async(dispatch_get_main_queue(), ^{
          NSLog(@"Background task expired");
          if (self.backgroundTimer)
          {
              [self.backgroundTimer invalidate];
              self.backgroundTimer = nil;
          }
          [application endBackgroundTask:self.backgroundTask];
          self.backgroundTask = UIBackgroundTaskInvalid;
      });
  }];
  
  dispatch_async(dispatch_get_main_queue(), ^{
      self.backgroundTimer = [NSTimer scheduledTimerWithTimeInterval:10 target:self selector:@selector(timerUpdate:) userInfo:nil repeats:YES];
  });
  
  }
  
  
  - (void) timerUpdate:(NSTimer*)timer {
      UIApplication *application = [UIApplication sharedApplication];
  
      NSLog(@"Timer update, background time left: %f", application.backgroundTimeRemaining);
  
      if ([application backgroundTimeRemaining] &lt; 60 &amp;&amp; !self.didShowDisconnectionWarning)
      {
          UILocalNotification *localNotif = [[UILocalNotification alloc] init];
          if (localNotif) {
              localNotif.alertBody = @"Background session will expire in one minute.";
              localNotif.alertAction = @"OK";
              localNotif.soundName = UILocalNotificationDefaultSoundName;
              [application presentLocalNotificationNow:localNotif];
          }
          self.didShowDisconnectionWarning = YES;
      }
      if ([application backgroundTimeRemaining] &lt; 10)
      {
          // Clean up here
          [self.backgroundTimer invalidate];
          self.backgroundTimer = nil;
  
          [application endBackgroundTask:self.backgroundTask];
          self.backgroundTask = UIBackgroundTaskInvalid;
      }
  
  }
  </code></pre>