2012-03-06 27 views
4

這可能會是一些簡單的我失蹤得到的位置,但我有位置服務設置爲左右(縮短清晰度):的iOS CLLocation - 在viewDidLoad中

- (void)viewDidLoad 
{ 
    self.locationManager = [[[CLLocationManager alloc] init] autorelease]; 
    self.locationManager.delegate = self; 
    [self.locationManager startUpdatingLocation]; 
} 

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation 
{ 
    NSLog(@"%@",newLocation.coordinate.latitude); 
    NSLog(@"%@",newLocation.coordinate.longitude); 
} 

工作正常並給我一個位置數據流到日誌。

但我想要的是能夠立即在ViewDidLoad中獲取當前位置,因爲我只需要它一次,而不是一個常量更新 - 它只是查明「最近」的舒適度,以便我可以報告回用戶。我試過在startUpdatingLocation後立即向ViewDidLoad添加:

self.locationLat = [self.locationManager location].coordinate.latitude; 
self.locationLng = [self.locationManager location].coordinate.longitude; 

但是它們總是以空值出現。有沒有其他事情我必須打電話來獲取數據,一旦它運行?

感謝

回答

2

你將只能得到值

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation 

沒有其它功能可讓位置值..所以你會得到價值最快的是當此功能首次調用...

+0

對,所以我必須將我的代碼移到那裏。好的,我會放棄這一點,並使用上面羅馬的建議來確保它不是連續的流。 – Dave 2012-03-06 10:54:59

10
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation 
{ 
    /*report to user*/ 
    [self.locationManager stopUpdatingLocation]; 
} 

所以你會得到位置一次,然後停止更新它。

3
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation 
{ 
    [manager stopUpdatingLocation]; 
    NSLog(@"%@",newLocation.coordinate.latitude); 
    NSLog(@"%@",newLocation.coordinate.longitude); 
}