我正在尝试在我的应用程序中启用后台定位模式。我在我的 plist 文件中启用了“位置更新”后台模式。该应用程序包含一个每 15 秒更新一次的计时器。
当应用程序导航到后台时,我正在执行以下操作
- (void)applicationDidEnterBackground:(UIApplication *)application {
UIApplication* app = [UIApplication sharedApplication];
self.bgTaskID = [app beginBackgroundTaskWithExpirationHandler:^{
NSLog(@"background task %lu expired", (unsigned long)self.bgTaskID);
[app endBackgroundTask:self.bgTaskID];
self.bgTaskID = UIBackgroundTaskInvalid;
}];
[NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(initializeLocationManager) userInfo:nil repeats:NO];
if(self.timerLocationBackground)
{
[self.timerLocationBackground invalidate];
self.timerLocationBackground = nil;
}
self.timerLocationBackground = [NSTimer scheduledTimerWithTimeInterval:15
target:self
selector:@selector(initializeLocationManager)
userInfo:nil
repeats:YES];}`
初始化位置管理器如下
-(void)initializeLocationManager
{
if(!self.locationManager)
self.locationManager = [[CLLocationManager alloc] init];
else
[self.locationManager stopUpdatingLocation];
if ((![CLLocationManager locationServicesEnabled])
|| ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusRestricted)
|| ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusDenied))
{
//user has disabled his location
}
else
{
self.locationManager.delegate = self;
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
self.locationManager.distanceFilter = kCLDistanceFilterNone;
[self.locationManager setAllowsBackgroundLocationUpdates:YES];
[self.locationManager startUpdatingLocation];
}
}
当我在 10 分钟后导航回应用程序时,我的计时器在 3 分钟停止,这是应用程序暂停的时间。
当应用程序回到前台时我的代码如下:
- (void)applicationWillEnterForeground:(UIApplication *)application {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
//
//Remove the baground task
//
if (self.bgTaskID != UIBackgroundTaskInvalid) {
[[UIApplication sharedApplication] endBackgroundTask:self.bgTaskID];
self.bgTaskID = UIBackgroundTaskInvalid;
}
[self.locationManager stopUpdatingLocation];
有什么帮助吗?