【问题标题】:iOS CoreLocation in backgroundiOS CoreLocation 在后台
【发布时间】:2017-01-21 15:50:53
【问题描述】:
我正在开发一个位置跟踪应用程序。用户可以开始跟踪,做任何他想做的事情(将应用程序置于后台,锁定手机等),返回应用程序并停止跟踪。
如果应用被(系统或用户)杀死,我希望重新启动跟踪。为此,我在文档中看到我必须使用重大位置更改服务,但该服务没有发送足够的位置。由于重要的位置更改服务,重新启动应用程序时是否可以重新启动标准位置服务?还是应用会被拒绝?
【问题讨论】:
标签:
ios
background
core-location
kill
【解决方案1】:
即使在后台被杀死,以下方法也会唤醒您的应用程序:
- 区域事件
- 参观活动
- 重要的位置事件
您的应用程序将使用applicationDidFinishLaunchingWithOptions 方法中的位置键启动。这是一个如何优雅地处理它的示例(来自http://nshipster.com/launch-options/):
// .h
@import CoreLocation;
@interface AppDelegate () <CLLocationManagerDelegate>
@property (readwrite, nonatomic, strong) CLLocationManager *locationManager;
@end
// .m
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// ...
if (![CLLocationManager locationServicesEnabled]) {
[[[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Location Services Disabled", nil)
message:NSLocalizedString(@"You currently have all location services for this device disabled. If you proceed, you will be asked to confirm whether location services should be reenabled.", nil)
delegate:nil
cancelButtonTitle:NSLocalizedString(@"OK", nil)
otherButtonTitles:nil] show];
} else {
self.locationManager = [[CLLocationManager alloc] init];
self.locationManager.delegate = self;
[self.locationManager startMonitoringSignificantLocationChanges];
}
if (launchOptions[UIApplicationLaunchOptionsLocationKey]) {
[self.locationManager startUpdatingLocation];
}
}
此外,您不限于使用重要位置监控或区域监控等。您可以针对不同的用例使用不同的机制。例如。您可以使用区域监控在用户周围设置一个后备区域,并且每次发生退出事件时,您的应用程序都会被 location 键唤醒。然后,您可以重新启动位置服务。