我想通过 postId
获取特定帖子。这可以用 firebase 和 swift 来做吗?
目前,我正在从 geofire 获取一把 key ,其中包含我想要的所有 postId key 。是否可以获取与这些 postIds
相关的帖子数据 这是我当前的尝试。我当前的尝试不会将任何帖子附加到我的 collectionView
var posts = [Post]()
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let userLocation: CLLocation = locations[0] as CLLocation
let currentUserLocation = userLocation
let circleQuery = geoFire?.query(at: currentUserLocation, withRadius: 100.0)
guard let uid = Auth.auth().currentUser?.uid else { return }
_ = circleQuery?.observe(.keyEntered, with: { (key, location) in
print(key)
let ref = Database.database().reference().child("posts")
var postId = key
ref.child(uid).child(postId).observe(.value, with: { (snapshot) in
self.collectionView?.refreshControl?.endRefreshing()
guard let dictionaries = snapshot.value as? [String: Any] else { return }
dictionaries.forEach({ (key, value) in
guard let dictionary = value as? [String: Any] else { return }
guard let user = Auth.auth().currentUser?.uid as? User else { return }
var post = Post(user: user, dictionary: dictionary)
post.id = key
self.posts.append(post)
self.posts.sort(by: { (post1, post2) -> Bool in
return post1.creationDate.compare(post2.creationDate) == .orderedDescending
})
})
}, withCancel: { (error) in
print("There was an error getting the posts:", error)
})
self.locationManager.stopUpdatingLocation()
})
}
最佳答案
使用快照haschild来检查
let ref = Database.database().reference().child("posts")
ref.observeSingleEvent(of: .value, with: { (snapshot) in
if snapshot.hasChild("\(self.yourValueToCompare!)"){
print("Exists in Database")
}else{
print("Does not Exists in Database")
}
})
关于swift - 从帖子 ID firebase 和 swift 获取帖子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53291089/