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

paj*_*vic 36 iphone cllocationmanager ios-4.2

如何检查用户是否允许mu app的位置?通常我会使用该类的authorizationStatus方法CLLocationManager,但它仅适用于iOS 4.2及更高版本.是否有可能在使用SDK 4.2时以某种方式实现此目的,以便应用程序仍然可以在具有旧版iOS的设备上运行,或者我是否必须降级SDK?沿着同一条线,我需要一个类似于locationServicesEnablediOS 4.0之前的方法的替代方案.

Mar*_*don 60

当您拨打电话时-startUpdatingLocation,如果用户拒绝了位置服务,则位置管理员代表将接收-locationManager:didFailWithError:带有kCLErrorDenied错误代码的呼叫.这适用于所有iOS版本.

  • @SpacyRicochet这回答了这个问题吗?OP询问如何确定是否为特定应用程序启用了位置服务,以及`[CLLocationManager locationServicesEnabled]`是否只测试设备范围的位置服务.`[CLLocationManager authorizationStatus]`测试应用程序特定的授权. (31认同)
  • 我更喜欢调用`[CLLocationManager locationServicesEnabled]`,如下所述.这样你可以防止不必要的电话. (18认同)
  • 对于在没有"先前iOS 4.2"约束的情况下偶然发现的用户,答案是:[CLLocationManager authorizationStatus] (7认同)

Eas*_*der 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];
    }
Run Code Online (Sandbox Code Playgroud)

  • 我认为这不是那么正确.[CLLocationManager locationServicesEnabled]告诉您所有应用程序的位置为On或Off,[CLLocationManager authorizationStatus]告知app是否有权检查位置.所以UIAlertView应该说打开位置而不是授权应用程序.但这很有用,谢谢@EasyCoder (7认同)

don*_*kim 7

嗯..我没想过用authorizationStatus或者locationServicesEnabled.我做的是以下内容:

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;
}
Run Code Online (Sandbox Code Playgroud)

我很高兴看到有更好的检查方法,但是如果我的应用程序被允许使用GPS,我的方式没有任何问题.

希望这可以帮助!