如何从Firebase 5,Swift 4.2的GeoFire数据中获取附近的Feed?

时间:2019-01-24 15:47:16

标签: swift firebase geofire

我是GeoFire的新手。我想在获取附近的帖子供稿时获得一些反馈。 我的问题是: 1)Geofire数据库字符串具有Optional(“”)。是因为有多余的字符串(例如“ Optional(“”)“)而无法获取帖子的原因吗?如果是的话,是否有要删除的东西?

2)g下的字符串是什么:我必须将其包括在发布节点中吗?

3)我无法从以下代码中获取帖子。 “ print(self.keyArray.count)”和“ print(距离为任意)”工作正常。但是,当我尝试在“ POSTS_REF ....”之后打印snapshot.value时,它显示为“ null”。有人可以建议我一种方法来获取附近的帖子吗?

我在Firebase上的Geofire节点如下所示:enter image description here Optional(“”)中的字符串是我的postId。 我获取附近帖子的逻辑是: 1,确定我当前的位置:

func determineMyCurrentLocation() {
    locationManager.startUpdatingLocation()
}

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    locationManager.stopUpdatingLocation()
    if(currLocation == nil)
    {
        currLocation = locations.last
        self.fetchNearbyPost()
    }
    else{
        print("trying to update")
    }
}

2,我获取附近的帖子:

func fetchNearbyPost() {
    self.posts.removeAll()
    self.keyArray.removeAll()
    circleQuery = geoFire.query(at: currLocation, withRadius: 1000)
    var distanceArray = [Double]()
    circleQuery.observe(.keyEntered) { (key: String!, location: CLLocation!) in
        self.keyArray.append(key)
    }
    self.dispatchGroup.enter()
    circleQuery.observeReady {
        if(self.keyArray.count > 0)
        {
            for index in 0...self.keyArray.count-1{
                self.geoFire.getLocationForKey(self.keyArray[index], withCallback: { (keyLocation, error) in
                    print(self.keyArray.count)

                    let distance = keyLocation?.distance(from: self.currLocation)
                    distanceArray.append(distance!)
                    print(distance as Any)
                })
                POSTS_REF.child(self.keyArray[index]).observeSingleEvent(of: .value, with: { (snapshot) in
                    var post = Post(snapshot: snapshot)
                    post.distance = distanceArray[index]
                    self.posts.append(post)
                    if(self.keyArray.count == self.posts.count)
                    {
                        self.dispatchGroup.leave()
                    }
                    })
                })
            }
        }
        else
        {
            self.dispatchGroup.leave()
        }
    }

    dispatchGroup.notify(queue: .main) {
        self.posts = self.posts.sorted(by: { $0.distance < $1.distance })
        self.collectionView.reloadData()
        self.currLocation = nil
    }
}

0 个答案:

没有答案