简体   繁体   中英

How to check if location services are enabled for a particular app prior to iOS 4.2?

How can I check if the user has allowed location for mu app? Normally I would use authorizationStatus method of the CLLocationManager class, but it is only available in iOS 4.2 and newer. Is it possible to achieve this somehow while still using SDK 4.2, so that the app can still run on devices with older versions of iOS, or do I have to downgrade the SDK? And along the same line, I need a similar alternative for the locationServicesEnabled method prior to iOS 4.0.

When you call -startUpdatingLocation , if location services were denied by the user, the location manager delegate will receive a call to -locationManager:didFailWithError: with the kCLErrorDenied error code. This works both in all versions of iOS.

I've combined two techniques in the code below

    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];
    }

Hmm.. I didn't think to use authorizationStatus or locationServicesEnabled . What I did was the following:

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;
}

I'm glad to see there's a better method to check, but I haven't had any problems with the way I detect if my app is allowed to use the GPS.

Hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM