2016-11-13 39 views
-1

我使用下面的代碼來獲得一個按鈕緯度和經度0稱爲Objective-C的第二次

-(CLLocationCoordinate2D) getLocation{ 
    CLLocationCoordinate2D coordinate; 
    CLLocationManager *locationManager = [[CLLocationManager alloc] init]; 
    locationManager.delegate = self; 
    if ([CLLocationManager locationServicesEnabled]) { 
     locationManager.desiredAccuracy = kCLLocationAccuracyBest; 
     locationManager.distanceFilter = kCLDistanceFilterNone; 
     [locationManager startUpdatingLocation]; 
     [locationManager startUpdatingLocation]; 
     CLLocation *location = [locationManager location]; 
     coordinate = [location coordinate]; 
    } 
    else { 
     coordinate.latitude = 0.0; 
     coordinate.longitude = 0.0; 
    } 

    return coordinate; 
} 

當點擊第一次按鈕的點擊座標時,我得到我的但如果我再次單擊該按鈕,經度和緯度值爲0.0000 任何建議

+0

當你在XCode中進行調試時會發生什麼?是否因爲[CLLocationManager locationServicesEnabled]計算結果爲'false'而調用'else'子句?還是因爲'[位置座標]'返回'0,0'?當你從'[locationManager location]'返回時,你確定'location'不是null嗎? – selbie

+0

此外,文檔暗示您應該僅爲整個應用程序實例化一個CLLocationManager實例。您似乎在每次點擊按鈕時都會創建一個新的。 – selbie

+0

我確認if條件滿足調試期間.. – user1966460

回答

0

請在方法外初始化CLLocationManager。讓您可以在viewdidload方法中初始化。 它可以幫助你

0

你不能指望[locationManager location]到激活位置經理[locationManager startUpdatingLocation]後立即返回任何有用的東西。

CLLocationManager需要時間來獲取位置。您需要設置CLLocationManager的委託(例如,設置爲「self」),然後使用委託方法- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations;在位置管理器獲得可以使用的位置時得到通知。

參見:https://developer.apple.com/reference/corelocation/cllocationmanagerdelegate/1423615-locationmanager?language=objc

(如果你只想要一個位置,而不是位置更新的連續流,而不是調用「startUpdatingLocation」呼叫[locationManager requestLocation] - 但即使如此,你仍然需要使用委託方法是在獲得地點時通知)。

您需要將創建和啓動位置管理器的代碼拆分爲僅運行一次的位置(只需要一個位置管理器) - 例如viewDidLoad。然後,代碼的其餘部分處理獲取的位置應該放在委託方法中。

實際上,如果您希望您按鈕點擊以立即擁有位置,您需要讓位置管理員運行並更新位置,然後才能點擊按鈕。例如,啓用您的按鈕= NO,當您通過代理方法開始獲取位置時,將按鈕設置爲啓用= YES。