2015-12-10 83 views
2

已更新iOS9:我是iOS新手,嘗試使用CoreLocation返回經度和緯度值。下面的代碼永遠不會執行日誌輸出經緯度未找回

-(void)viewWillAppear:(BOOL)animated{ 

manager = [[CLLocationManager alloc]init]; 

manager.delegate = self; 
manager.desiredAccuracy = kCLLocationAccuracyBest; 

[manager startUpdatingLocation]; 
} 

這裏是我的永遠達不到

- (void)locationManager:(CLLocationManager *)manager 
didUpdateLocations:(NSArray<CLLocation *> *)locations{ 

NSLog(@"Location: %@", locations); 
CLLocation *currentLocation = locations.lastObject; 

if (currentLocation != nil) { 
    float latitude = currentLocation.coordinate.latitude; 

    float longitude = currentLocation.coordinate.longitude; 

    NSLog(@"dLongitude : %f", longitude); 
    NSLog(@"dLatitude : %f", latitude); 
} 

else{ NSLog(@"ERROR"); 
    } 

}

+0

使用實際的設備,而不是模擬器 –

+0

需要實現'CLLocationManager'委託提供你拉長信息。你不能直接得到它。有關更多詳細信息,請參閱[蘋果文檔](https://developer.apple.com/library/ios/documentation/CoreLocation/Reference/CLLocationManagerDelegate_Protocol/index.html) –

+0

@ sam-b我在設備上測試,我也更新了我的代碼爲iOS 9並且仍然有問題 – themotjuste

回答

1

CLLocationManager是異步的,你應該得到這個代表的緯度和經度didUpdateToLocation功能方法。

locationManager.delegate = self;

然後實現這個委託方法:

- locationManager:didUpdateLocations:

+0

因此,我需要將我的代碼移至locationManager:didUpdateLocations? – themotjuste

+0

@themotjuste將此代碼移至委託方法。 float latitude = locationManager.location.coordinate.latitude; float longitude = locationManager.location.coordinate.longitude; NSLog(@「dLongitude:%f」,longitude); NSLog(@「dLatitude:%f」,latitude); – Vincent

+0

出於某種原因,應用程序永遠不會到達委託方法 – themotjuste

1

所有1.首先,你應該用你應該使用,而不是一個模擬器

2.implement一個實際設備CLLocationManagerDelegate在界面中,如

@interface XXXXX() <CLLocationManagerDelegate> 

3.after

locationManager = [[CLLocationManager alloc] init]; 

添加

locationManager.delegate = self; 

4.implement委託方法

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations 
{ 
    for (CLLocation *location in locations) { 
     //you can get locations here 

    } 
} 
+0

我更新了我的代碼以顯示我的新didUpdateLocation函數,但未達到。另外,我正在測試我的設備。 – themotjuste