Search code examples
iphoneobjective-ciosxcodelong-polling

Long Polling and applicationDidEnterBackground:


I'm writing a very Simple Chat Application and would like to know how to suspend the long polling selector when the Application enters background.

Currently, I have a Chatroom class (A UIView) which handles the long polling like so:

-(void)startPolling
{
    [self performSelectorInBackground:@selector(longPoll) withObject: nil];
}

- (void) longPoll {
    
    //Poll the Requested URL...
        
    NSData* responseData = [NSURLConnection sendSynchronousRequest:request
                                                 returningResponse:&response error:&error];
    
    [self performSelectorOnMainThread:@selector(dataReceived:) 
                           withObject:responseData waitUntilDone:YES];
    [self performSelectorInBackground:@selector(longPoll) withObject: nil];
}

-(void) dataReceived: (NSData*) data
{    
   //Reload my Tableview etc.. 
}

How do I use applicationDidEnterBackground: to suspend the longPoll selector until the application comes back to the foreground? Or is this automatically done by the Application Delegate?


Solution

  • The request will automatically be suspended. It's not guaranteed that the request will necessarily succeed after being resumed, so you'll have to handle errors, but it shouldn't break.

    Note that there are probably better ways to write this than using performSelectorInBackground:, which always spins up a new hardware thread. For starters, it's probably better to simply loop inside longPoll instead of starting a new thread for the new request.