2014-12-26 157 views
-1

我想根據我的座標獲取我當前的位置。我在我的viewController中實施CLLocationManager,名爲myLocation。 我的問題是,我第一次沒有得到我的座標,但是當我再次接近時,我得到了座標。我無法理解這個問題,爲什麼這不是第一次出現。 我也試過給NSTimerstoplocation,但是仍然無法第一次得到結果,每次我得到一個(空)值,然後得到座標。獲取座標CLLocationManager IOS

我的代碼:

#import <UIKit/UIKit.h> 
#import <Corelocation/CoreLocation.h> 
@interface myLocation : UITableViewController<CLLocationManagerDelegate> 
@property (strong, nonatomic) CLLocationManager *locationManager; 

@end 

@interface myLocation() { 
    CLLocationManager* _locationManager; 
    NSString * _lat; 
    NSString * _lng; 
} 
@end 

@implementation myLocation 

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    _locationManager = [[CLLocationManager alloc] init]; 
    _locationManager.distanceFilter = kCLDistanceFilterNone; 
    _locationManager.delegate = self; 
    _locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters; 
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) 
     [_locationManager requestWhenInUseAuthorization]; 

    [_locationManager startUpdatingLocation]; 

} 
- (void)locationManager:(CLLocationManager *)manager 
    didUpdateLocations:(NSArray *)locations { 
    CLLocation *location = [locations lastObject]; 
    [_locationManager stopUpdatingLocation]; 
    _lat =[NSString stringWithFormat:@"%f",location.coordinate.latitude]; 
    _lng =[NSString stringWithFormat:@"%f",location.coordinate.longitude]; 
} 
- (void)viewWillAppear:(BOOL) animated 
{ 
NSLOG(@"%@",_lat); 
NSLOG(@"%@",_lng);  
} 
+0

哦,你的意思是爲什麼你的座標打印在viewWillAppear? –

+0

是的,只有第一次。 @LyndseyScott – developer

回答

1

你的座標沒有出現然而,當您嘗試打印他們viewWillAppear:因爲CLLocationManager已經沒有足夠的時間來檢索的第一個位置呢。等到didUpdateLocations:在嘗試利用設備座標之前首先調用,因爲didUpdateLocations:是您將接收這些座標的地方。我建議刪除您嘗試打印viewWillAppear中的座標代碼,然後直接在didUpdateLocations:中打印它們。

在評論中,OP表示他想在viewWillAppear期間「刷新」該位置。我建議停止更新時的視野中消失,並儘快重新出現視圖重啓更新:

- (void)viewWillAppear:(BOOL) animated 
{ 
    [_locationManager startUpdatingLocation]; 
} 

- (void)viewWillDisappear:(BOOL) animated 
{ 
    [_locationManager stopUpdatingLocation]; 
} 
+0

你的支持對我來說是可以接受的,在我的情景中仍有一點點問題。我只是在viewWillAppear中調用,以便每次新加載時,只要點擊它,它就會刷新。一個可能的情況,如果用戶沒有互聯網連接,那麼他得到後,他可以做些什麼來刷新。對此有何建議? – developer

+0

我得到了解決方案,在viewwillapear初始化幫助我。謝謝 – developer

+1

@ user3166680我實際上只是輸入一個類似的建議,但不需要完全重新初始化您的位置管理器。我已經更新了我的回答,並建議在視圖消失並重新出現時停止並重新啓動位置經理。 –

0

這需要一些時間位置服務啓動,並調用你的委託方法 - 這幾乎可以肯定不會發生如果您只在viewDidLoad開始位置服務,則會調用viewWillAppear。此外,您的應用第一次執行時,必須等待用戶授予權限。

您可以檢查CLLocationManagerlocation屬性以獲取最新的位置。如果它是nil那麼沒有確定位置(尚)。