首页 > 解决方案 > Firebase 和 Swift 限制帖子编号错误

问题描述

我试图将要获取的帖子数量限制为 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()
            })
        })

标签: swiftfirebasefirebase-realtime-database

解决方案


我认为这条线

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)

推荐阅读