通过试验 Core Location 框架经过数月的试验和错误,我找到了即使在应用程序被终止/暂停时也能获取位置更新的解决方案。它适用于 iOS 7 和 8。
这是解决方案:-
如果您的应用是基于位置的移动应用,需要在设备发生重大变化时监控设备的位置,则当设备从最后一个已知位置移动超过 500 米时,iOS 会返回一些位置坐标。是的,即使应用程序被用户或 iOS 本身杀死/暂停,您仍然可以获得位置更新。
所以为了让locationManager即使在应用程序被杀死/暂停时也能获得位置更新,你必须使用startMonitoringSignificantLocationChanges方法,你不能使用startUpdatingLocation。
当 iOS 想要将位置更新返回给应用程序时,它会帮助您重新启动应用程序并将密钥 UIApplicationLaunchOptionsLocationKey 返回到应用程序委托方法 didFinishLaunchingWithOptions。
密钥UIApplicationLaunchOptionsLocationKey 非常重要,你必须知道如何处理它。您必须在收到密钥时创建一个新的 locationManager 实例,您将在 locationManager 委托方法didUpdateLocations 上获得位置更新。
这里是示例代码:-
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
self.shareModel = [LocationShareModel sharedModel];
if ([launchOptions objectForKey:UIApplicationLaunchOptionsLocationKey]) {
self.shareModel.anotherLocationManager = [[CLLocationManager alloc]init];
self.shareModel.anotherLocationManager.delegate = self;
self.shareModel.anotherLocationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation;
self.shareModel.anotherLocationManager.activityType = CLActivityTypeOtherNavigation;
if(IS_OS_8_OR_LATER) {
[self.shareModel.anotherLocationManager requestAlwaysAuthorization];
}
[self.shareModel.anotherLocationManager startMonitoringSignificantLocationChanges];
}
return YES;
}
除了didFinishLaunchingWithOptions 方法之外,我还在应用程序处于活动状态时创建了locationManager 实例。以下是一些代码示例:
- (void)applicationDidEnterBackground:(UIApplication *)application
{
[self.shareModel.anotherLocationManager stopMonitoringSignificantLocationChanges];
if(IS_OS_8_OR_LATER) {
[self.shareModel.anotherLocationManager requestAlwaysAuthorization];
}
[self.shareModel.anotherLocationManager startMonitoringSignificantLocationChanges];
}
- (void)applicationDidBecomeActive:(UIApplication *)application
{
if(self.shareModel.anotherLocationManager)
[self.shareModel.anotherLocationManager stopMonitoringSignificantLocationChanges];
self.shareModel.anotherLocationManager = [[CLLocationManager alloc]init];
self.shareModel.anotherLocationManager.delegate = self;
self.shareModel.anotherLocationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation;
self.shareModel.anotherLocationManager.activityType = CLActivityTypeOtherNavigation;
if(IS_OS_8_OR_LATER) {
[self.shareModel.anotherLocationManager requestAlwaysAuthorization];
}
[self.shareModel.anotherLocationManager startMonitoringSignificantLocationChanges];
}
我写了一篇文章,详细解释了如何在 iOS 7 和 8 中获取位置更新,即使应用程序被终止/挂起。我还在 GitHub 上上传了完整的源代码,其中包含有关如何测试此解决方案的步骤。
请访问以下网址了解更多信息:-
- Getting Location Updates for iOS 7 and 8 when the App is Killed/Terminated/Suspended
- Source Code on GitHub - Get the Location Updates Even when the iOS mobile apps is Suspended/Terminated/Killed