Firebase和Swift限制发布数错误

时间:2019-02-13 00:49:52

标签: swift firebase firebase-realtime-database

我正试图将要获取的帖子数量限制为4个,但是由于某种我不知道的原因,它返回的内容比限制为4个帖子的要多,而单元格内部没有任何数据。但是,如果最后删除.queryLimited(toLast: 4)查询,则可以正常运行,但会加载所有帖子。我在做什么错了?

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    let userLocation:CLLocation = locations[0] as CLLocation

    guard let uid = Auth.auth().currentUser?.uid else { return }

    let lat = userLocation.coordinate.latitude
    let lon = userLocation.coordinate.longitude

    let loc1: CLLocationDegrees = lat
    let loc2: CLLocationDegrees = lon
    let myLocation: CLLocation = CLLocation(latitude: loc1, longitude: loc2)

    let myQuery = geoFire?.query(at: myLocation, withRadius: 100)

    var queryHandler = myQuery?.observe(.keyEntered, with: { (key:String!, location:CLLocation!) in

        let ref = Database.database().reference().child("posts").child(key).observe(.value, with: { (snapshot) in

            let postId = snapshot.key
            self.fetchPosts(with: postId)
            self.locationManager.stopUpdatingLocation()
        })
    })
}

fileprivate func fetchPosts(with postId: String) {
    self.collectionView?.refreshControl?.endRefreshing()

    guard let currentUid = Auth.auth().currentUser?.uid else { return }

    //inital data pull
    if currentKey == nil {

        let ref = Database.database().reference().child("posts").child(postId).queryLimited(toLast: 4)
        ref.observe(.value, with: { (snapshot) in

            guard let dict = snapshot.value as? [String: Any] else { return }

            guard let uid = dict["uid"] as? String else { return }

            Database.fetchUserWithUID(uid: uid, completion: { (user) in
                guard let dictionary = snapshot.value as? [String: Any] else { return }

                var post = Post(postId: snapshot.key, user: user, dictionary: dictionary)

                let postId = snapshot.key
                post.id = snapshot.key

                self.posts.append(post)

                self.posts.sort(by: { (post1, post2) -> Bool in
                    return post1.creationDate.compare(post2.creationDate) == .orderedDescending
                })
                self.collectionView?.reloadData()
            })
        })

1 个答案:

答案 0 :(得分:1)

我认为这条线

let ref = Database.database().reference().child("posts").child(postId).queryLimited(toLast: 4)

接受postId下的最后4个孩子。

如果您只想发表4条帖子,可以尝试将.queryLimited(toLast:4)移到此引用的末尾,即您第一次查询“帖子”的地方:

let ref = Database.database().reference().child("posts").child(key)