swift - 从帖子 ID firebase 和 swift 获取帖子

标签 swift firebase firebase-realtime-database geofire

我想通过 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()
    })
}

Firebase database

最佳答案

使用快照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/

相关文章:

ios - 更新到 Swift 2.0 'map' 不可用 : call the 'map()' method on the sequence

python - Socketswift 连接到特定 IP 地址超时

android - 在不保留信息的情况下保持 Firebase 同步状态

ios - 如何更新嵌入到 UIKit 中的 SwiftUI View ?

Swift:切换 View 后使用 UILongPressGestureRecognizer 时应用程序崩溃

javascript - 如何使用 JavaScript 有条件地将过滤器应用于 Firestore 查询

java - 非常简单的 Firestore 事务失败

javascript - Firebase 代码 400 "message": "CONFIGURATION_NOT_FOUND"

android - Firebase Android Studio (2.2.3) 问题

java - Android Firebase java.lang.StackOverflowError : stack size 8MB error when user is uploading an image