位置管理器未显示允许权限

时间:2015-04-28 15:22:18

标签: ios gps location

我是一名新手程序员,试图让位置管理器工作。首先,我认为我需要"允许使用位置"盒子出来了。我已导入CoreLocation,将locationManager设置为委托,将所需精度设置为Best,并设置startUpdatingLocation。我还在Info.plist中添加了文本隐私 - 位置使用说明。根据Apple iOS Developer库,这就是我需要做的。我想,一旦我获得“允许权限”框并单击“允许”,我就可以开始添加代码以使用GPS位置。使用Xcode 8.3。 附:将代码放在这里可以吗?

2 个答案:

答案 0 :(得分:0)

答案 1 :(得分:0)

首先检查授权状态(根据documentation):

- (BOOL)checkLocationServicesAuthorizationStatus
{
    switch ([CLLocationManager authorizationStatus])
    {
        case kCLAuthorizationStatusNotDetermined:
            [self requestLocationServicesUseAuthorization];
            return NO;
        case kCLAuthorizationStatusAuthorizedWhenInUse:
        case kCLAuthorizationStatusAuthorizedAlways:
            return YES;
        case kCLAuthorizationStatusRestricted:
        case kCLAuthorizationStatusDenied:
        default:
            return NO;
    }
}

首次使用者的状态不确定,因此您需要申请正确的授权:

- (void)requestLocationServicesUseAuthorization NS_AVAILABLE_IOS(8_0)
{
#if LOCATION_ALWAYS_REQUIRED
    if ([self.locationManager respondsToSelector:@selector(requestAlwaysAuthorization)])
    {
        [self.locationManager requestAlwaysAuthorization];
    }
#else
    if ([self.locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)])
    {
        [self.locationManager requestWhenInUseAuthorization];
    }
#endif
}

委托回调在接受权限对话框后开始更新位置非常方便:

- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status
{   
    if([CLLocationManager locationServicesEnabled] && [self checkLocationServicesAuthorizationStatus])
    {
        [self.locationManager startUpdatingLocation];
    }
}

还应检查CLLocationManager上的+locationServicesEnabled类方法,以确保首先启用位置服务。

相关问题