PerformSelector After delay doesn't run in background mode - iPhone

Idan picture Idan · Oct 9, 2011 · Viewed 11k times · Source

I have a voip application which runs constantly on the background as well. While I'm in the background I'm calling from the main thread: (to establish network connection in case I diagnose a network lost).

[self performSelector :@selector(Reconnect:) withObject:nil afterDelay:60.0];

However, the selector is only performed when my app returns to foreground. Should I do anything in particular to make the selector getting executed while in the background ?

Thanks

Edit:

-(void) reconectInBackgroundAfterDelay:(NSTimeInterval) dealy
{
    NSLog(@"reconectInBackgroundAfterDelay");
    UIApplication*   app = [UIApplication sharedApplication];

    bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
        [app endBackgroundTask:bgTask];
        bgTask = UIBackgroundTaskInvalid;
    }];

    // Start the long-running task and return immediately.
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

        [self performSelector :@selector(Reconnect:) withObject:nil afterDelay:dealy];

        [app endBackgroundTask:bgTask];
        bgTask = UIBackgroundTaskInvalid;
    });
}

I added this code instead, but still the "Reconnect" method is not getting called after the provided delay. I call the "reconectInBackgroundAfterDelay" method while I'm already in the background.

Any other suggestions ?

Edit 2 Found a solution. See below

Answer

Idan picture Idan · Oct 10, 2011

The only solution I found so far :

 dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ 

        NSTimer* t = [NSTimer scheduledTimerWithTimeInterval:1 target:self  selector:@selector(Reconnect:) userInfo:nil repeats:NO];    

        [[NSRunLoop currentRunLoop] addTimer:t forMode:NSDefaultRunLoopMode];

        [[NSRunLoop currentRunLoop] run]; 
    });