Search code examples
iosobjective-cxcodebackground-processappdelegate

iOS - trying to get app running in background indefinitely


I'm trying to get an app running indefinitely.. I'm developing an internal app, so apple approval doesnt matter.

I've tried a few different things, including simulating a voip app using this tutorial..

http://www.raywenderlich.com/29948/backgrounding-for-ios

Eventually I ran into this code snippet online

[application beginBackgroundTaskWithExpirationHandler:^{}];

I place this in beginBackgroundTaskWithExpirationHandler and then call a slow-looping function inside of my app delegate in application:didFinishLaunchingWithOptions

-(void)caller{

    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 3 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
        NSTimeInterval timeRemaining = [UIApplication sharedApplication].backgroundTimeRemaining;
        NSLog(@"%f", timeRemaining);
       [self caller];
    });
}

this logs background time remaining every 3 seconds. it does this when i exit my app.. i see a countdown from 180 (3 minutes) to eventually 0

then it just keeps logging 0 indefinitely. I would figure if background time reaches zero, then my process wouldnt execute.

Anyone have any idea whats going on here?


Solution

  • If you use beginBackgroundTaskWithExpirationHandler and start the app from Xcode, that will alter the behavior of this UIBackgroundTaskIdentifier (Xcode will keep the app alive). If you see the log messages showing up in Xcode's debugging console, that means the app was started on the device via Xcode.

    Now that the app is installed on the device, stop it (either by hitting the "stop" button in Xcode or by manually terminating the app via Springboard on the device). Once you've confirmed the app isn't running, you can now run it again by tapping the app icon on the device itself. It should start, not linked to Xcode in any way.

    Even though the app is now not running via Xcode, though, you can still monitor the progress of what you logged, by going to Xcode's "Device Organizer", and open up the actual device's console. I suspect you'll see the background task expire, like you expected it to.