在我的应用程序中,我需要在后台执行位置更新。为此,我将我的位置跟踪对象注册为观察者,如下所示:
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(start)
name:UIApplicationDidEnterBackgroundNotification
object:nil];
这是开始更新位置的方法:
- (void)start
{
NSInteger downloadsCount = [[SGDataManager sharedInstance] countOfActiveDownloads];
NSInteger uploadsCount = [[SGDataManager sharedInstance] countOfActiveUploads];
if (downloadsCount + uploadsCount > 0)
{
[self.locationManager startUpdatingLocation];
}
}
但是位置更新永远不会开始。但是,如果我将 UIApplicationDidEnterBackgroundNotification
更改为 UIApplicationWillResignActiveNotification
,那么位置更新将在后台完美运行。那么我该如何让它为 did enter 后台通知工作呢?
我要注意我的应用程序启用了位置更新后台模式
最佳答案
当您的应用程序进入后台时,它完成任务的时间是有限的。在那之后,任务将被暂停。
尝试将您的 UpdateLocation
放入后台任务中,如下所示:
http://hayageek.com/ios-long-running-background-task/
此示例还在进入后台时使用位置更新。
编辑:
在我看来,这是一个 CoreLocation
错误。它可能是这样的:startUpdatingLocation
方法完成,后台任务完成,但 CoreLocation
产生的其他线程中仍有一些事情发生并且应用程序挂起该线程,因为它进入后台。不过这只是一个猜测。
无论哪种方式,这里有一个解决方法:在后台延长您的应用程序生命周期。 startUpdatingLocation
完成后不要结束后台任务,让它运行几秒钟。
__block UIBackgroundTaskIdentifier back = [application beginBackgroundTaskWithExpirationHandler:^{
[application endBackgroundTask: back];
back = UIBackgroundTaskInvalid;
}];
[manager startUpdatingLocation];
此代码将使您的应用在后台运行几分钟。如果你愿意,你可以创建一个可以更快暂停它的计时器
NSTimer* killBackgroundTaskTimer = [NSTimer scheduledTimerWithTimeInterval: 10 target: self
selector: @selector(killBackgroundTask:) userInfo: nil repeats: NO];
-(void) callAfterSixtySecond:(NSTimer*) t
{
[application endBackgroundTask: back];
back = UIBackgroundTaskInvalid;
}
关于ios - 当应用程序确实进入后台时,CLLocationManager 不会开始位置更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28743443/