如何在 iOS 4.2 之前检查特定应用程序是否启用了位置服务?

36

如何检查用户是否允许应用程序使用其位置?通常,我会使用 CLLocationManager 类的 authorizationStatus 方法,但它仅适用于 iOS 4.2 及更高版本。在仍然使用 SDK 4.2 的情况下,是否可以以某种方式实现此目标,以便该应用程序仍然可以在旧版 iOS 设备上运行,还是必须降级 SDK? 另外,我需要一个类似的选项来替代 iOS 4.0 之前的 locationServicesEnabled 方法。

3个回答

60
当您调用-startUpdatingLocation时,如果用户拒绝了位置服务,则位置管理器委托将收到一个带有错误代码kCLErrorDenied-locationManager:didFailWithError:调用。这适用于所有iOS版本。

18
我更喜欢以下描述中提到的调用 [CLLocationManager locationServicesEnabled] 的方式,这样可以避免不必要的调用。 - SpacyRicochet
7
针对那些没有“iOS 4.2之前”的限制而来到这里的用户,答案是:[CLLocationManager authorizationStatus]。 - fionbio
31
@SpacyRicochet这个回答是否解答了问题?OP问了如何确定某个应用程序是否启用了位置服务,而[CLLocationManager locationServicesEnabled]只是测试设备范围内的位置服务。[CLLocationManager authorizationStatus]则测试特定应用程序的授权状态。 - NSTJ
1
@SpacyRicochet,[CLLocationManager locationServicesEnabled]仅检查一般的“位置服务”开关,而不检查单个应用程序的状态。 - LiangWang
@nous 现在是 kCLAuthorizationStatusDenied - dclowd9901

37

我在下面的代码中结合了两种技术

    MKUserLocation *userLocation = map.userLocation;
    BOOL locationAllowed = [CLLocationManager locationServicesEnabled];
    BOOL locationAvailable = userLocation.location!=nil;

    if (locationAllowed==NO) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Location Service Disabled" 
                                                        message:@"To re-enable, please go to Settings and turn on Location Service for this app." 
                                                       delegate:nil 
                                              cancelButtonTitle:@"OK" 
                                              otherButtonTitles:nil];
        [alert show];
        [alert release];
    } else {
        if (locationAvailable==NO) 
            [self.map.userLocation addObserver:self forKeyPath:@"location" options:(NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld) context:nil];
    }

与上述问题相同。请不要假设空用户位置表示未授权,因为这可能并不准确。 - millenomi
7
我认为这并不是完全正确。[CLLocationManager locationServicesEnabled]会告诉你所有应用程序的位置功能是开启还是关闭,而[CLLocationManager authorizationStatus]则告诉你该应用程序是否有权限检查位置信息。因此,UIAlertView 应该提示打开位置功能而不是授权应用程序。但是这很有用,谢谢@EasyCoder。 - Mário Carvalho

7

哦,我没有想到可以使用authorizationStatuslocationServicesEnabled。我的做法如下:

MKUserLocation *userLocation = mapView.userLocation;

if (!userLocation.location) {
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Location Service Disabled" 
                                                    message:@"To re-enable, please go to Settings and turn on Location Service for this app." 
                                                   delegate:nil 
                                          cancelButtonTitle:@"OK" 
                                          otherButtonTitles:nil];
    [alert show];
    [alert release];
    return;
}

我很高兴看到有一种更好的方法来检查,但是我检测我的应用程序是否被允许使用GPS的方式还没有出现任何问题。

希望这能帮到您!


1
请注意,即使启用了位置服务,用户的位置可能无法使用。例如,用户可能在所有传感器的覆盖范围之外(例如没有Wi-Fi的iPod touch)。 - millenomi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接