Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 423
Idan Avatar asked Oct 09 '11 13:10

Idan


3 Answers

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]; 
    }); 
like image 54
Idan Avatar answered Oct 05 '22 02:10

Idan


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.

like image 29
Akshay Avatar answered Oct 05 '22 03:10

Akshay


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.

like image 42
DDZ Avatar answered Oct 05 '22 04:10

DDZ