ios - 当应用程序确实进入后台时,CLLocationManager 不会开始位置更新

标签 ios objective-c cocoa-touch core-location

在我的应用程序中,我需要在后台执行位置更新。为此,我将我的位置跟踪对象注册为观察者,如下所示:

 [[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/

相关文章:

ios - 将文档目录的路径传递给 xcode 运行脚本

iphone - setUserTrackingMode 在 MKMapView 上带有注释很慢

iphone - NSCache崩溃的应用程序

ios - 使用#define,好的做法?

iphone - MediaPlayer 或 AVFoundation 最终停止工作

iphone - 为什么我的 UIAlertView 仅在延迟后才出现?

ios - Facebook SDK 4.4.0 logInWithReadPermissions无法在iOS 9的iPhone上使用

objective-c - 发现运行应用程序的环境和相对路径

objective-c - 如何检测 UITableViewCellStyleSubtitle 样式中 UITableViewCell 对象的 UIImageView 上的触摸

ios - UITableView - 更改部分标题颜色