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
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];
});
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With