支持iOS6到9中的后台位置更新

时间:2015-10-06 10:47:49

标签: ios objective-c swift cllocationmanager background-task

是否可以支持从iOS6.0到新iOS9的后台位置更新?

此外,即使应用关闭或设备被锁定,也可以让应用在后台更新位置?

你能给我一些关于如何做的文件吗?

提前致谢!

更新

我已经从here下载了一个示例项目,但由于某种原因,即使使用模拟位置并移动超过500米,它也不会在后台更新位置。所以我改变了这两种方法:

- (void)startMonitoringLocation {
    if (_anotherLocationManager)
        [_anotherLocationManager stopMonitoringSignificantLocationChanges];

    self.anotherLocationManager = [[CLLocationManager alloc]init];
    _anotherLocationManager.delegate = self;
    _anotherLocationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation;
    _anotherLocationManager.activityType = CLActivityTypeOtherNavigation;

    if(IS_OS_8_OR_LATER) {
        [_anotherLocationManager requestAlwaysAuthorization];
    }
    [_anotherLocationManager startMonitoringSignificantLocationChanges];
}

- (void)restartMonitoringLocation {
    [_anotherLocationManager stopMonitoringSignificantLocationChanges];

    if (IS_OS_8_OR_LATER) {
        [_anotherLocationManager requestAlwaysAuthorization];
    }
    [_anotherLocationManager startMonitoringSignificantLocationChanges];
}

而不是使用stopMonitoringSignificantLocationChangesstartMonitoringSignificantLocationChanges,我现在使用stopUpdatingLocationstartUpdatingLocation。问题是,现在当我要去背景时,它开始获取位置并且永远不会停止。为什么呢?

2 个答案:

答案 0 :(得分:2)

是的,这是可能的,但为什么你需要使用IOS 6,我不知道,顺便提一下你想在后台发送位置更新这个代码会帮你完成这个

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    bgTask = [application beginBackgroundTaskWithName:@"MyTask" expirationHandler:^{

    // Clean up any unfinished task business by marking where you
    // stopped or ending the task outright.

    [application endBackgroundTask:bgTask];
    bgTask = UIBackgroundTaskInvalid;
}];

// Start the long-running task and return immediately.
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

    // Do the work associated with the task, preferably in chunks.

    [application endBackgroundTask:bgTask];
    bgTask = UIBackgroundTaskInvalid;
});
}

答案 1 :(得分:0)

该应用需要注册后台模式以进行位置更新。

请参阅Background Execution chapter in the App Programming Guide for iOS