Objective C - CLLocationManager find out when “Allow” or “Don't allow” is clicked

妖精的绣舞 提交于 2019-12-03 16:34:58

There is a delegate method for that

- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status {
    if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorized) {
        // user allowed
    }

}

[CLLocationManager locationServicesEnabled] only tells your if the location service are enabled on the device.

[CLLocationManager authorizationStatus] returns the actual status you're looking for.

You'll have to implement didFailWithError: method:

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {

    if ([error domain] == kCLErrorDomain) {

        // We handle CoreLocation-related errors here
        switch ([error code]) {
        // "Don't Allow" on two successive app launches is the same as saying "never allow". The user
        // can reset this for all apps by going to Settings > General > Reset > Reset Location Warnings.
        case kCLErrorDenied:

        case kCLErrorLocationUnknown:

        default:
            break;
        }

    } else {
    // We handle all non-CoreLocation errors here
    }
}

EDIT: Looking at CLLocationManager's reference I've found this:

+ (CLAuthorizationStatus)authorizationStatus

Return Value A value indicating whether the application is authorized to use location services.

Discussion The authorization status of a given application is managed by the system and determined by several factors. Applications must be explicitly authorized to use location services by the user and location services must themselves currently be enabled for the system. This authorization takes place automatically when your application first attempts to use location services.

locationManager.locationServicesEnabled indicates whether location services is available, but not necessarily mean they are allowed for your app.

Use CLLocationManager.authorizationStatus() if you need to find out the status at a point in time, or implement

- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status;

Take note since iOS 8, the authorization request does not takes place automatically when your application first attempts to use location services. You need to call requestWhenInUseAuthorization() explicitly before you call startUpdatingLocation() on your CLLocationManager instance.

And make sure you have the NSLocationAlwaysUsageDescription or NSLocationWhenInUseUsageDescription key in Info.plist, depending on the type of authorization you are after. If these are missing, there are no errors, no logs, no hints, no nothing that will point you in the right direction :)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!