Firebase和Swift限制帖子号码错误

问题描述 投票:0回答:1

我试图限制我的帖子数量达到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()
            })
        })
swift firebase firebase-realtime-database
1个回答
1
投票

我觉得行

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

将最后4个孩子带到postId下。

如果您只想要4个帖子,您可以尝试将.queryLimited(toLast:4)移动到此参考的末尾,您首先查询“帖子”:

let ref = Database.database().reference().child("posts").child(key)
© www.soinside.com 2019 - 2024. All rights reserved.