8

如何獲取當前位置的經緯度。如何在IOS SDK 8.0中獲取當前位置的經緯度

我試試這個。使用Xcode 6.01和IOS SDK 8.0

-(CLLocationCoordinate2D) getLocation{ 
    locationManager = [[CLLocationManager alloc] init]; 
    locationManager.delegate = self; 
    locationManager.desiredAccuracy = kCLLocationAccuracyBest; 
    locationManager.distanceFilter = kCLDistanceFilterNone; 
    [locationManager startUpdatingLocation]; 
    CLLocation *location = [locationManager location]; 
    CLLocationCoordinate2D coordinate = [location coordinate]; 
    return coordinate; 
} 

- (void)getCurrentLocation{  
    CLLocationCoordinate2D coordinate = [self getLocation]; 
    NSString *latitude = [NSString stringWithFormat:@"%f", coordinate.latitude]; 
    NSString *longitude = [NSString stringWithFormat:@"%f", coordinate.longitude]; 
    NSLog(@"Latitude = %@", latitude); 
    NSLog(@"Longitude = %@", longitude); 
} 


- (void)viewDidLoad{ 
    [super viewDidLoad]; 
    [self getCurrentLocation]; 

} 

在這裏,我啓用模擬器位置部署8.0 iPhone模擬器4s。 即使在設備上它不工作。

@ALL 請讓我知道,我在這裏做錯了什麼。

回答

0

是的,模擬器提供了過度簡化的定位服務。物理設備是真正測試CLLocationManager行爲的唯一方法。

問題是,當您撥打startUpdatingLocation時,這並不意味着您可以立即檢索location。 (我想你會發現它要麼nil或具有負horizontalAccuracy,這意味着尚未確定的位置。)

必須符合CLLocationManagerDelegate,並實現locationManager:didUpdateLocations:,這是異步調用。因此,在嘗試使用位置信息之前,您必須等待調用此方法。並且,請注意,在真實設備上,隨着設備精確度提高(例如,您可能會看到horizontalAccuracy號碼從一個位置更新到另一個位置),您可能會看到此設備改進設備位置信息的次數。


顯然,您可能也想要實施locationManager:didFailWithError:,因此可以檢測到問題。在致電startUpdatingLocation之前,您可能還應該檢查authorizationStatus,locationServicesEnabled,並致電requestWhenInUseAuthorization

0

看來我們需要做更多的任務來在ios8中實現位置服務。 follow this discussion

+0

加入既代表方法didFailWithError和didUpdateToLocation但這方法不觸發在所有 – KkMIW 2014-10-02 16:16:25

+0

請在您的.h文件中添加CLLocationManagerDelegate,像這樣@interface DemoViewController:UIViewController Samin 2014-10-03 03:13:48

+0

我添加了CLLocationManagerDel egate,我仍然有問題。升級sdk IOS 7到IOS 8後出現問題。 – KkMIW 2014-10-03 10:26:48

5

我搞清楚問題IOS 8.0

NSLocationAlwaysUsageDescription添加此手動進入應用plist文件,請將字符串值空。 這將調用委託方法。永遠不會忘記添加NSLocationAlwaysUsageDescription除非你沒有添加這個委託方法將無法正常工作。剩餘的代碼是相同的。將委託方法添加到控制器類中。

將這行代碼添加到locationManager聲明代碼中。對於IOS 8.0 [locationManager requestAlwaysAuthorization];

3

在iOS 8中,此代碼無法自動失敗即,您將不會收到任何錯誤或警告。

你需要做兩個額外的事情讓位置工作:

  1. 添加鍵從位置管理要求它開始你的Info.plist
  2. 請求授權

需要在Info.plist文件中添加以下任意一個或兩個鍵。

  1. NSLocationWhenInUseUsageDescription
  2. NSLocationAlwaysUsageDescription

這些是字符串類型和值的可以是任何消息描述或爲空。

現在您需要爲相應的位置方法請求授權。使用以下任一要求:

  1. [self.locationManager requestWhenInUseAuthorization]
  2. [self.locationManager requestAlwaysAuthorization]
+0

不錯的一個.... !!節省了很多時間 – 2015-05-13 22:01:17

相關問題