2012-01-17 102 views

回答

5

只是爲了完成添的回答。

您可以隨時嘗試通過CLLocationManager實例上的startUpdatingLocation方法啓動位置更新。如果位置服務被禁用,你就會收到通知有關委託錯誤情況,然後你可以彈出對話框,要求用戶進入設置,併爲您的應用啓用位置服務,...

#pragma mark - CLLocationManagerDelegate 
- (void)locationManager:(CLLocationManager *)inManager didFailWithError:(NSError *)inError{ 
    if (inError.code == kCLErrorDenied) { 
     NSLog(@"Location manager denied access - kCLErrorDenied"); 
     // your code to show UIAlertView telling user to re-enable location services 
     // for your app so they can benefit from extra functionality offered by app 
    } 
} 

請注意,您可以通過iOS5上的URL方案啓動設置應用程序(低於5.0(和高於5.0)的版本,不支持它)。致電:

[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"prefs://"]]; 
+0

注意,在打開的首選項只能在安裝iOS 5.0,而不是之前,而不是之後 - 見http://stackoverflow.com/questions/736047 /編程,開放的 - 設置 - 應用程序 - iPhone – Rayfleck 2013-11-01 15:48:18

9

按照docs,CLLocationManager有一個靜態方法,看看是否LocationServices啓用:

+ (BOOL)locationServicesEnabled 
1

在嘗試更新位置之前,您可以檢查位置服務是否已啓用。

這裏是我使用的代碼片段:

if (TARGET_IPHONE_SIMULATOR) { 
    currentLocation = [[CLLocation alloc] initWithLatitude:37.331718 longitude:-122.030629]; 
    [self methodNameHere:currentLocation]; 
} else { 
    if ([CLLocationManager locationServicesEnabled]) { 
     [locationManager startUpdatingLocation]; 
    } else { 
     UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Location Services Disabled" message:@"Enable location services to do this" delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil]; 
     [alert show]; 
     [alert release]; 
    } 
} 

基本上,代碼檢查,如果你的目標模擬器,如果你嘗試獲得位置,可以給你的錯誤,所以不是我只是硬編碼我想模擬的位置(在這種情況下,蘋果總部)。如果定位設備,則會檢查位置服務是否已啓用,如果是,則會調用您要執行的方法,如果不是,則會向用戶顯示警報消息。

0

我想一個更好的方式來處理這將是這樣:

switch ([CLLocationManager authorizationStatus]) { 
    case kCLAuthorizationStatusAuthorizedWhenInUse: 
    case kCLAuthorizationStatusAuthorizedAlways: 
     //we're good to go 
     break; 
    default: 
     //pop up an alert 
     break; 
} 
相關問題