您在这里有两个选择:
1)定期位置跟踪。
这种类型的跟踪适用于kCLAuthorizationStatusAuthorizedWhenInUse
and kCLAuthorizationStatusAuthorizedAlways
授权。什么时候CLLocationManager
一旦在委托方法中收到位置更新,就开始跟踪位置locationManager:didUpdateLocations:
。应用程序可以进入挂起状态,但是当位置管理器收到新位置时,应用程序将进入后台状态并在委托方法中处理新位置。如何设置位置管理器:
- (void)viewDidLoad {
[super viewDidLoad];
self.locationManager = [[CLLocationManager alloc] init];
// Setup location tracker accuracy
self.locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation;
// Distance filter
self.locationManager.distanceFilter = 50.f;
// Assign location tracker delegate
self.locationManager.delegate = self;
// This setup pauses location manager if location wasn't changed
[self.locationManager setPausesLocationUpdatesAutomatically:YES];
// For iOS9 we have to call this method if we want to receive location updates in background mode
if([self.locationManager respondsToSelector:@selector(allowsBackgroundLocationUpdates)]){
[self.locationManager setAllowsBackgroundLocationUpdates:YES];
}
[self.locationManager startUpdatingLocation];
}
2) 意义位置变化跟踪。
这种类型的跟踪仅适用于kCLAuthorizationStatusAuthorizedAlways
授权。它仅每 500 米接收一次新位置,因此距离过滤器和desiredAccuracy 在这里不起作用。应用程序可以进入挂起状态,甚至可以被系统终止,但是当位置更新时,应用程序进入后台状态并在委托方法中接收位置locationManager:didUpdateLocations:
.
如果应用程序被系统终止,它将在后台重新启动UIApplicationLaunchOptionsLocationKey
键入启动选项didFinishLaunchingWithOptions
应用程序委托方法。如何在跟踪上设置此类型:
- (void)viewDidLoad {
[super viewDidLoad];
self.locationManager = [[CLLocationManager alloc] init];
// Assign location tracker delegate
self.locationManager.delegate = self;
// For iOS9 we have to call this method if we want to receive location updates in background mode
if([self.locationManager respondsToSelector:@selector(allowsBackgroundLocationUpdates)]){
[self.locationManager setAllowsBackgroundLocationUpdates:YES];
}
[self.locationManager startMonitoringSignificantLocationChanges];
}
您应该注意到,这两种方法都不能保证您的应用程序不会进入挂起状态。
此外,如果应用程序被用户终止(例如通过滑动从应用程序切换器终止),后台位置跟踪将无法工作。
UPDATE(对应评论)
这是适合我的代码示例:
用于定期跟踪 https://github.com/shpasta/location-tutorial-part-1。运行示例,提供对用户位置的访问,点击Start按钮开始位置更新。要测试模拟器中的位置,请在模拟器菜单中选择“调试”>“位置”>“高速公路驱动器”。现在您可以通过主页按钮(Command+Shift+H)将应用程序推送到后台。离开模拟器超过 10 分钟,应用程序将一直接收位置信息。当您返回应用程序时,您将在地图上看到红色图钉。
对于重大变更 https://github.com/shpasta/location-tutorial-part-2。运行应用程序并按照与前面示例相同的方式进行测试。
监控重大变化只能通过方法启动[self.locationManager startMonitoringSignificantLocationChanges];
UPDATE(iOS 11)
iOS 11 中位置跟踪的更改
iOS 11 还对现有 API 进行了一些重大更改。受影响的领域之一是位置跟踪。如果您的应用仅在应用处于前台时使用位置与大多数应用程序一样,您可能根本不需要更改任何内容;但是,如果它是全天连续跟踪用户位置的应用程序之一,您可能应该在今年夏天预订一些时间,对跟踪和测试可能的使用场景的方式进行一些更改。
请点击此链接:https://mackuba.eu/2017/07/13/changes-to-location-tracking-in-ios-11/ https://mackuba.eu/2017/07/13/changes-to-location-tracking-in-ios-11/