【问题标题】:iOS: Track user locationiOS:跟踪用户位置
【发布时间】:2015-10-29 19:02:37
【问题描述】:

我在很多应用中都使用过定位服务,但这个新应用在 iOS 8.0 及更高版本上存在问题。我没有收到有关应用程序首次加载提示以允许定位服务的通知。但是,在我的 iOS 7.1 设备上,我得到了提示。

这是我的 appDelegate 在 didFinishLaunchingWithOptions 中的内容:

self.locationManager = [CLLocationManager new];
[self.locationManager setDelegate:self];
if ([self.locationManager respondsToSelector:@selector(requestAlwaysAuthorization)]) {
    [self.locationManager requestAlwaysAuthorization];
}

[self initializeRegionMonitoring];

而initializeRegionMonitoring方法是:

-(void) initializeRegionMonitoring {

NSLog(@"initialize region monitoring");

self.locationManager = [[CLLocationManager alloc] init];
self.locationManager.delegate = self;

// radius of region being monitored
CLLocationDistance radius = 25; // 20 metre sensitivity
CLLocationCoordinate2D coordinate;
coordinate.latitude = 25.886099;
coordinate.longitude = -80.165124;

self.someRegion = [[CLCircularRegion alloc] initWithCenter:coordinate radius:radius identifier:@"Qualex"];
self.someRegion.notifyOnEntry = YES;
self.someRegion.notifyOnExit = YES;
[self.locationManager startMonitoringForRegion:self.someRegion];

// notify changes when the device has moved x meters
self.locationManager.distanceFilter = 20; // or set to 20 meters
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
self.locationManager.activityType = CLActivityTypeAutomotiveNavigation;
[self.locationManager startUpdatingLocation];
[self.locationManager startMonitoringSignificantLocationChanges];
}

我还在 info.plist 中设置了 NSLocationAlwaysUsageDescription,所以肯定有什么我忘记了,对吧?感谢您的帮助!

编辑:

我同时也在注册远程通知,这以前从来不是问题,但我认为这可能是一些有用的额外信息。

此外,当应用程序终止时,重新运行通知以允许位置服务弹出,但会立即消失。只是在屏幕上闪烁。我不知道为什么它会在不单击警报上的选项之一的情况下关闭。

【问题讨论】:

  • 您是否打算在initializeRegionMonitoring 方法中替换您的locationManager 实例?第二个实例永远不会调用requestAlwaysAuthorization,这可能是您的问题的根源。
  • 您真的打算像这样使用两个不同的位置管理器吗?
  • @thelaws 这应该没关系。位置授权在当前应用程序中跨所有 CLLocationManager 实例是全局的。用户授予始终在线位置访问权限后,所有位置管理员都将拥有该访问权限
  • @n00neimp0rtant 感谢您的澄清
  • 在设置窗口之前还是之后提示用户?

标签: ios objective-c cllocationmanager


【解决方案1】:

在 iOS 8 之前,您可以简单地通过实例化 CLLocationManager 对象并尝试启动位置跟踪来请求位置权限。在 iOS 8 及更高版本上,这不会出现权限提示;您必须使用requestAlwaysAuthorizationrequestWhenInUseAuthorization 方法手动请求授权。

话虽如此,在 iOS 8 上,如果您调用其中任何一个方法,那么您调用它的 CLLocationManager 实例将被释放,位置权限提示将自行关闭。这里发生的是您正在创建一个位置管理器,请求权限(iOS 开始尝试显示权限对话框),调用initializeRegionMonitoring,并将self.locationManager 属性设置为一个新的位置管理器实例。这会导致您创建的第一个被 ARC 释放,因此权限提示在它有机会出现之前就被忽略了。

删除self.locationManager = [[CLLocationManager alloc] init]; 方法中的initializeRegionMonitoring 行应该可以解决问题。

【讨论】:

  • AFAIK,CLLocationManager 的这个怪癖和授权过程没有记录,所以 +1 对你的问题 :)
猜你喜欢
  • 2016-11-14
  • 1970-01-01
  • 2014-03-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多