我想获取设备的当前位置。代码工作正常。如果用户未更改位置服务的应用程序授权状态,则会提供位置。我也可以检查用户是否拒绝了位置服务的许可。
问题是用户取消对应用的授权以使用位置服务,然后再次授权。在这种情况下,在此之后,如果我尝试获取位置,它会提供nil
,但它会调用
- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status
状态为3
的委托方法,即kCLAuthorizationStatusAuthorized
。
获取当前位置的代码:
CLLocation * location = self.locationManager.location;
Getter方法:
- (CLLocationManager *)locationManager
{
if (!locationManager)
{
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
}
return locationManager;
}
CLLocationManager委托方法:
- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status
{
DLog(@"Location authorization changed : %d", status);
// If user has denied permission for location service
if (status == kCLAuthorizationStatusDenied)
{
DLog(@"Location service denied.");
// If authorization status changed method is already called, then SDK will not call again on same object.
// Thus, set CLLocationManager object to nil so that next time we try to get location, it will create a new object,
// and that will send message about authorization status changed.
self.locationManager.delegate = nil;
self.locationManager = nil;
}
else if (status == kCLAuthorizationStatusNotDetermined)
{
// If authorization status changed method is already called, then SDK will not call again on same object.
// Thus, set CLLocationManager object to nil so that next time we try to get location, it will create a new object,
// and that will send message about authorization status changed.
self.locationManager.delegate = nil;
self.locationManager = nil;
}
else if (status == kCLAuthorizationStatusAuthorized)
{
}
}
对此有何想法?
答案 0 :(得分:0)
self.locationManager.location
是nil
,因为您从未开始更新该位置。
在apple docs中,陈述了locationManager的location
属性:
如果没有位置数据,则此属性的值为nil 检索。
出于这个原因,你需要以某种方式更新你的iPhone位置!
通常这意味着您要打电话
[self.locationManager startUpdatingLocation]
但您也可以使用
[self.locationManager startMonitoringSignificantLocationChanges]
答案 1 :(得分:0)
如果您将委托设置为nil,您将无法获得有关授权状态更改的更新,不是吗?
self.locationManager.delegate = nil;
我认为您应该保留委托以便接收授权状态更新,然后调用startUpdatingLocation方法以获取当前位置。
- (void)startUpdatingLocation