2014-02-11 53 views
0

我使用CLLocationManager來獲得設備的當前位置,我試圖讓location物業,以獲得的經度和緯度如下:CLLocationManager沒有得到位置

-(void)getCurrentLocation{ 
CLLocationManager *manager=[[CLLocationManager alloc]init];; 
manager.delegate=self; 
manager.desiredAccuracy=kCLLocationAccuracyBest; 
self.currentLocation=manager.location; 
NSLog(@"Current Lat :%f",self.currentLocation.coordinate.latitude); 
NSLog(@"Current Long :%f",self.currentLocation.coordinate.longitude); 

[manager startUpdatingLocation]; 
} 

鑑於:

self.currentLocation is a property inside my class (Which is the CLLocationManagerDelegate) as follows: 

.H

@property(nonatomic,strong) CLLocation *currentLocation; 

並在.M吸氣劑是如下:

-(CLLocation *)currentLocation{ 
if (!_currentLocation) { 
    _currentLocation=[[CLLocation alloc]init ]; 
} 
return _currentLocation; 

} 

我忘了說我已經實現了didUpdateToLocation方法如下:

-(void)locationManager:(CLLocationManager *)manager 
didUpdateToLocation:(CLLocation *)newLocation 
     fromLocation:(CLLocation *)oldLocation { 
NSLog(@"didUpdateToLocation"); 
CLLocation *loc=newLocation; 
if (loc!=nil) { 
    self.currentLocation=loc; 

} 

} 

我也試圖把這個聲明startUpdateLocation調用之後:

self.currentLocation=manager.location; 

問題是,當我打電話給以前的功能getCurrentLocation其內的兩個NSLogs打印0.000000這意味着manager.location不工作,奇怪的是,第一個NSLog裏面didUpdateToLocation不打印,預先感謝

+0

你應該實現'CLLocationManagerDelegate'方法(特別是'locationManager:didUpdateLocations:')並且等到你在那裏調用。您應該查看啓動位置管理器並等待響應的過程作爲異步過程。 – Rob

+0

請注意,didUpdateToLocation自iOS 6.0起棄用!相反,請使用didUpdateLocations。 您的問題是您的代理方法直到以後的時間點才被調用。可能是10毫秒,或幾秒鐘。取決於GPS信號等。 嘗試並將NSLog調用移動到委託方法中,如下例所示。 – MartinHN

回答

1

你不能只從CLLocationManager讀取位置。它需要更新其位置被分配屬性之前:

The value of this property is nil if no location data has ever been retrieved. 

CLLocationManager SDK

您必須實現委託方法locationManager:didUpdateLocations:

,這就是所謂的時,你可以閱讀location財產,或者看看在locations說法:

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations { 
    self.currentLocation = [locations firstObject]; 

    NSLog(@"Current Lat :%f",self.currentLocation.coordinate.latitude); 
    NSLog(@"Current Long :%f",self.currentLocation.coordinate.longitude); 

    [manager stopUpdatingLocation] 
} 

您可以撥打[manager stopUpdatingLocation]當你接到第一個電話時,它不會繼續運行。

+0

已編輯 –

+0

@JavaPlayer您的問題仍然是,您在嘗試從GPS中檢索位置之前嘗試讀取位置。此外,您正在使用不贊成使用的委託方法,正如我在上面的評論中所解釋的。 嘗試執行我上面的委託方法,看看會發生什麼。 – MartinHN

+0

我試過了,它在模擬器上運行良好,但它不能在設備上工作(didUpdateLocations方法未被調用!)雖然我打開設備的位置服務 –