2017-01-10 44 views
0

在我的主要CollectionView(應用程序主頁)上,我想根據距離用戶最近的位置更新位置(即單元格本身)。我將我的位置存儲在Firebase中,並將使用GeoFire和核心位置,以便按距離順序正確列出距離用戶的位置。在viewVillAppear中加載GeoFire查詢的用戶位置數據

其他職位都表示,觀察員的最佳做法涉及將其加載到viewWillAppear;但是,在運行之前,我無法獲取用戶的位置,並且沒有我的GeoFire查詢的中心點。與CoreLocation相關的大多數示例都涉及地圖或預選座標,但我並未打算在此控制器內使用地圖,並且希望根據用戶位置動態加載。

我已經研究了加載didUpdateLocationsAppDelegate之內,但是還沒有能夠在那裏調用那個方法。在加載viewWillAppear中返回的數據時運行GeoFire查詢之前獲取用戶位置座標的最佳方法是什麼?或者您是否需要設置區域並檢查用戶是否在該區域內輸入?

var locationDict = [CLLocation]() //using this variable to pass values outside the function to the query   
    override func viewWillAppear(animated: Bool) { 
     locationManager.desiredAccuracy = kCLLocationAccuracyBest 
     locationManager.requestAlwaysAuthorization() 
     locationManager.startUpdatingLocation() 
    } 


    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { 
    let recentLocation = locations[0] 
    locationDict.append(recentLocation)  
    } 

    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) { 

     print(error.localizedDescription) 

} 
+0

我有同樣的問題,通過獲取viewWillAppear中和在viewDidAppear觀察者的位置來解決它。在查詢Firebase之前,我還檢查了我的位置是否有效。 –

+0

你會如何從viewpoint的核心位置獲取位置?我需要使用.requestLocation的位置管理器方法嗎?你能告訴我你如何克服這個問題的基本代碼嗎? – Josh

回答

0

有相當多的在你的代碼丟失,但在短(什麼工作對我來說):

.requestLocation在viewWillAppear中

.startUpdatingLocation()在viewDidAppear。 (所以兩次)。

var justStartedUsingMap = true 

在didUpdateLocations:

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]){ 

    guard let myLocation:CLLocation = manager.location else {return} 
    let location:CLLocationCoordinate2D = myLocation.coordinate 
    let region = MKCoordinateRegion(center: location, span: MKCoordinateSpan(latitudeDelta: 0.12, longitudeDelta: 0.12)) 

    if justStartedUsingMap == true { 
     self.currentLocationSearch(myLocation) 
     justStartedUsingMap = false 
    } else { 
     locationManager.stopUpdatingLocation() 
    } 

    self.map.setRegion(region, animated: true) 
} 

func currentLocationSearch(_ location: CLLocation) { 
    // the geofire observer 
} 
+0

從你對這個問題[http://stackoverflow.com/questions/41449938/how-to-remove-a-geofire-handle-for-the-following-observe-in-swift]如何正確地移除手柄對於Swift 3中的GeoFire,因爲文檔似乎沒有更新。當你使用'locationManager.location'時,只有一次拉動座標? – Josh

+0

@Josh不,它會繼續拉座標,因此我把一個var justStartedUsingMap = true,並放在如果justStartedUsingMap = true {如果self.locationsIndex == 0 //等justStartedUsingMap = false} else {locationManager.stopUpdatingLocation()} ,毫不猶豫地把它寫在答案中,因爲我在某處讀到你不應該那樣做。 Jay也回答了這個問題,但只要你在地圖上移動,觀察者需要在附近找到新物體,觀察者就不會在viewDidDisappear上發佈。我縮小了觀察者的範圍。 –

+0

是的,我現在的主要問題是偶爾出現,我不確定爲什麼該位置返回一次,然後在返回到此視圖控制器時導致UI重複。你認爲我應該有條件地檢查我的本地數組是否等於特定的計數,如果不刪除舊的位置值? – Josh

相關問題