swift - 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()
})
})
解决方案
我认为这条线
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)
推荐阅读
- java - spring-boot-admin,版本和信息未显示
- django - 注册用户登录后如何在 Web 应用中实现 JWT 认证?
- arduino - 错误在'{'标记之前不允许函数定义:对于teensy 3.2 arduino
- r - 如何通过条件从列中创建表格?
- java - java正则表达式模式用空格“xxxx xxx xxx”格式化数字
- javascript - Javascript:如何在 // 和之前获取字符串的子字符串
- scikit-learn - 在用复合内核拟合 GuassianProcessRegressor 之后,我们可以只使用内核的一部分进行预测吗?
- html - 如何在 ReactJS 中选择一个空目录?
- android - 我如何使用 shape drawable 在 android 中制作这个形状
- c# - UWP 应用程序中的 ColorPaletteResources API - 如何通过代码而不是 Xaml 在应用程序资源中设置具有自己颜色的 ColorPaletteResources?