在viewWillAppear中加载GeoFire查询的用户位置数据

时间:2017-01-10 02:33:07

标签: ios swift firebase firebase-realtime-database geofire

在我的主CollectionView(应用主页)上,我想根据与用户最近的位置更新位置(即单元格本身)。我将我的位置存储在Firebase中,并将使用GeoFire和核心位置,以便从用户正确列出距离顺序的位置。

其他帖子表示,观察员的最佳做法是将其加载到viewWillAppear;但是,我在运行之前无法获取用户的位置,并且我的GeoFire没有居中点查询。大多数与CoreLocation相关的示例涉及地图或预选坐标,但我并未计划在此控制器中使用地图,而是希望根据用户位置动态加载。

我已在didUpdateLocations内研究加载AppDelegate,但无法在那里调用该方法。在GeoFire中加载返回的数据时,在运行viewWillAppear查询之前获取用户位置坐标的最佳方法是什么?或者您是否需要设置区域并检查用户是否已进入该区域?

    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)

}

1 个答案:

答案 0 :(得分:0)

你的代码中有很多缺失,但总之(对我有用):

viewWillAppear中的

.requestLocation

viewDidAppear中的

.startUpdatingLocation()。 (这么两次)。

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 
}
相关问题