2015-06-23 58 views
1

我創建了一個按鈕。點擊按鈕時,我想獲取我的位置。在使用位置管理器之前,我必須先徵求用戶的許可。請看看我的代碼:didChangeAuthorizationStatus在授權未更改時運行

- (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

回答

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