我创建了一个按钮。单击按钮时,我想获取我的位置。在使用位置管理器之前,我必须要求用户许可。请看我的代码:
- (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
。
答案 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];
}
}