Count while in background (NSTimer for more than 3 mins)

半腔热情 提交于 2019-12-06 19:47:25

You can do it by following way:

1) First include required background mode keys into your Info.plist

2) Check and add following line of code for adding background working of location manager in iOS 9 (update: also works in iOS 10):

if ([self.locationManager respondsToSelector:@selector(setAllowsBackgroundLocationUpdates:)]) {
    [self.locationManager setAllowsBackgroundLocationUpdates:YES];
    [self.locationManager pausesLocationUpdatesAutomatically:NO];
}

3)Then create a new timer with repeated continuously with every 1 sec.

4)In that timer method add these two line of code.

[self.locationManager stopUpdatingLocation];
[self.locationManager startUpdatingLocation];

This make your app run in background more than 3 mins. To be aware, the battery usage may be costly.

As of iOS 9, apps are allowed a maximum of 180 seconds (3 minutes) of background execution time upon request. This can be extended indefinitely if you put location updates in the “Required background modes” in your Info.plist. I have verified that doing so lets the background execution run forever. Having this in your Info.plist, however, will require you to get approval from Apple for this background mode before putting your app in the App Store.

If you don't want to request location background mode, there are some other tricks you can do to get around Apple's restrictions, which you can read about here: https://gooddevbaddev.wordpress.com/2013/10/22/ios-7-running-location-based-apps-in-the-background/

A word of caution about using those tricks, though -- they are subject to change in any iOS upgrade, and using them might get your app rejected by reviewers.

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