2010-08-04 20 views
8

我在設置面板中禁用了我的應用程序的位置服務。我在我的視圖控制器的viewDidLoad中運行測試以查看它們是否已啓用:locationServicesEnabled測試在viewDidLoad中被禁用時通過

if([CLLocationManager locationServicesEnabled]) { 
    //Do something now 
} 

此測試總是出於某種原因。如果我嘗試訪問位置服務,我會爲位置管理器收到kCLErrorDenied錯誤。是什麼賦予了?

我使用了錯誤的測試嗎?

回答

25

locationServicesEnabled class方法只測試位置服務的全局設置。 AFAIK,沒有辦法測試你的應用是否被明確拒絕。您必須等待位置請求失敗並使用CLLocationManagerDelegate方法locationManager:didFailWithError:來執行您所需的任何操作。例如: -

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

    NSString *errorString; 
    [manager stopUpdatingLocation]; 
    NSLog(@"Error: %@",[error localizedDescription]); 
    switch([error code]) { 
     case kCLErrorDenied: 
      //Access denied by user 
      errorString = @"Access to Location Services denied by user"; 
      //Do something... 
      break; 
     case kCLErrorLocationUnknown: 
      //Probably temporary... 
      errorString = @"Location data unavailable"; 
      //Do something else... 
      break; 
     default: 
      errorString = @"An unknown error has occurred"; 
      break; 
     } 
    } 

    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:errorString delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil]; 
    [alert show]; 
    [alert release]; 
} 

看到CLLocationManager class reference上CLError常量的文檔,更多的選擇。

+0

這是有道理的,爲什麼它總是返回true。謝謝! – Adam 2010-08-11 00:40:04

+0

@ Dan,如果locationServicesEnabled爲false,那麼我已經等了很長時間,但是不調用委託(locationManager:didFailWithError :)方法。是什麼原因?? – Apple 2012-06-28 06:17:49

20

iOS 4.2現在允許人們通過CLLocationManager方法確定位置服務是否被拒絕。

相關問題