在未更改授权时运行didChangeAuthorizationStatus

时间:2015-06-23 13:13:55

标签: ios cllocationmanager

我创建了一个按钮。单击按钮时,我想获取我的位置。在使用位置管理器之前,我必须要求用户许可。请看我的代码:

- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status {
    if (status == kCLAuthorizationStatusAuthorizedAlways || status == kCLAuthorizationStatusAuthorizedWhenInUse) {
        [self startGettingLocation];
    }
}

- (IBAction)locationButtonAction:(id)sender {
    if (status == kCLAuthorizationStatusAuthorizedAlways || status == kCLAuthorizationStatusAuthorizedWhenInUse) {
        [self startGettingLocation];
    } else if (status == kCLAuthorizationStatusNotDetermined) {
        [self.locationManager requestWhenInUseAuthorization];
    }
}

问题是方法locationManager:didChangeAuthorizationStatus在视图加载后运行!当用户没有点击按钮时,方法startGettingLocation即被启动。如果仅在用户点击按钮时更改此代码才能运行startGettingLocation

1 个答案:

答案 0 :(得分:3)

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    self.initialAuthorizationStatus = [CLLocationManager authorizationStatus];

    self.locationManager = [CLLocationManager new];
    self.locationManager.delegate = self;
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
}

- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status {
    // If status really did change.
    if (self.initialAuthorizationStatus != status) {
        if (status == kCLAuthorizationStatusAuthorizedAlways || status == kCLAuthorizationStatusAuthorizedWhenInUse) {
            [self startGettingLocation];
        }
    }
}


- (IBAction)locationButtonAction:(id)sender {
    if (status == kCLAuthorizationStatusAuthorizedAlways || status == kCLAuthorizationStatusAuthorizedWhenInUse) {
        [self startGettingLocation];
    } else if (status == kCLAuthorizationStatusNotDetermined) {
        [self.locationManager requestWhenInUseAuthorization];
    }
}