从postId firebase和Swift获取帖子

时间:2018-11-13 23:41:41

标签: swift firebase firebase-realtime-database geofire

我想通过postId来获取特定帖子。这与firebase和swift可能有关吗?

当前,我从geofire那里获取了一个密钥,该密钥具有我想要的所有postId密钥。是否可以获取与这些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()
    })
}

Firebase database

1 个答案:

答案 0 :(得分:0)

使用快照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")
        }
    })