【发布时间】:2016-10-26 17:25:51
【问题描述】:
我正在尝试在我的应用程序中启用后台定位模式。我在我的 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];}`
initializeLocationManager 在下面
-(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];
有什么帮助吗?
【问题讨论】:
-
你能把设置 self.bgTaskID 的代码贴出来吗?
-
@rjpadula 更新了,请检查,是在 didenterbackground 方法中设置的第一行
-
您能否看到“后台任务 %lu 已过期”消息是否正在显示?您可能需要更新后台任务。根据我的经验,三分钟是你需要多长时间。
-
@rjpadula 我该如何续订?位置检索不应该让应用保持清醒吗?
标签: ios cllocationmanager xcode8 uibackgroundtask background-mode