How do I make my App run an NSTimer in the background?

久未见 提交于 2019-11-27 03:36:28

I figured it out by myself, for anyone else with a similar problem, what I did was to first turn on the location update flag on your Info.plist file. To do this, you must add the Key called "Required Background Modes" on Xcode 4, then as a value, select "App registers for location updates"

I have a timer declared like so in my .h file:

NSTimer *silenceTimer;
@property (nonatomic, retain) NSTimer *silenceTimer;

Then on the .m file, I declared it like so:

UIBackgroundTaskIdentifier bgTask;
UIApplication  *app = [UIApplication sharedApplication];
bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
    [app endBackgroundTask:bgTask]; 
}];
self.silenceTimer = [NSTimer scheduledTimerWithTimeInterval:300 target:self
selector:@selector(startLocationServices) userInfo:nil repeats:YES];

Finally, on the selector method, I made the following:

-(void)startLocationServices {
    [locationManager startUpdatingLocation];
    [locationManager stopUpdatingLocation];
}

This will create a timer that starts and immediately stops location services after 5 minutes. This will be enough for the app to stay alive indefinately, unless you kill the process.

serge-k

XCode 6.3.1, for iOS 8.3

There are big diffrences that I've encountered between the apps. behavior while plugged in to your Mac running XCode using debugger and the same apps. behavior while unplugged.

At current iOS version, 8.3, at most your app is allotted is 180 seconds to run in the background for finite long running task with an expiration handler.

No matter what you try, with your phone unplugged your app will be killed by the system in 180 seconds or earlier. I've done a significant amounts of tests and tricks to confirm this. See my post...

My NSTimer Post

Here is a neat way to tell how much time is left for your app to run before termination, keep in mind that you are not guaranteed this time.

NSTimeInterval backgroundTimeRemaining = [[UIApplication sharedApplication] backgroundTimeRemaining];

if (backgroundTimeRemaining == DBL_MAX)
{
    NSLog(@"background time remaining = undetermined");
}
else
{
    NSLog(@"background time remaining = %0.2f sec.", backgroundTimeRemaining);
}

Hope this helps your investigation. Cheers!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!