Idan
Idan

Reputation: 5817

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

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

Upvotes: 10

Views: 11350

Answers (3)

DDZ
DDZ

Reputation: 11

I was test it for some time, found that in ios background run when an corebluetooth event coming, if you want to do something delay use NSTimer object,you must be less than 10 seconds, and if more than 10 seconds, the timer will be invalid.

Upvotes: 1

Idan
Idan

Reputation: 5817

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]; 
    }); 

Upvotes: 22

Akshay
Akshay

Reputation: 5765

Have you put this line in the beginBackgroundTaskWithExpirationHandler block? Have a look at th section Completing a Finite-Length Task in the Background at http://developer.apple.com/library/ios/#documentation/iphone/conceptual/iphoneosprogrammingguide/BackgroundExecution/BackgroundExecution.html.

Upvotes: 1

Related Questions