【问题标题】:Get value for specific keys in Firebase获取 Firebase 中特定键的值
【发布时间】:2017-11-30 19:43:55
【问题描述】:

我想使用数组的键从 Firebase 获取数据。我该怎么做呢?

我的 Firebase 数据库结构如下所示。

我只想在“LOCATIONS”获取钥匙的帖子。所以我将键存储在数组中的位置:

var nearbyPosts = [-L-9P7oUUs40qJLFSNyt, -L-9YwHX-RKZFIiyZ7sG] 

问题是,我如何使用这个数组中的键从帖子中获取数据?还是有其他方法可以做到?

我尝试过不同的查询尝试,例如:

let dbRef = DataService.ds.REF_POSTS.queryEqual(toValue: nearbyPosts).queryOrderedByKey()

let dbRef = DataService.ds.REF_POSTS.queryStarting(atValue: nearbyPosts.startIndex).queryEnding(atValue: nearbyPosts.endIndex).queryOrderedByKey()

【问题讨论】:

    标签: swift firebase firebase-realtime-database


    【解决方案1】:

    所以我不确定您所说的位置究竟是什么意思,但是当我想在特定位置检索数据时,我会这样做:

    Database.database().reference().child("posts/\(ourID!)/comment").observe(DataEventType.value, with: { (snapshot) in
    

    为了澄清:“帖子”是发布所有内容的分支。 'ourID' 是用户发布的特定帖子。 “评论”是帖子中的数据。

    看,帖子就是一切。长字符串是我的帖子,评论是我正在阅读的帖子中的一个值。在您的情况下,长字符串将是“位置”。希望这会有所帮助。

    Posts:
        4TBxDgN1Q4I4KNpp4
            Comment = "" 
            Date = "2017-11-29 01:51:31 +0000"
            Post = "This is an example post"
            User = "JDerbs"
    

    【讨论】:

    • 问题是我希望您的示例中的“ourID”是整个附近帖子的数组,所以我不必一次获得一个帖子。我有点想要这个:Database.database().reference().child("posts/(nearbyPosts)/comment"),但它不会让我这样做。努力解释,但希望你能理解。
    • 嗯,这就是我会做的......什么类型的错误。如果是我,我会在顶部创建一个数组,就像你想调用它一样。然后: var posts:[String] = [] Database.database().reference().child("posts/nearbyPosts").observe(DataEventType.value, with: { (snapshot) in print("***( snapshot)") if let item = snapshot.value as? String{ self.posts.append(item) } self.tableView.reloadData() }) 看到 cmets.append 的位置了吗?这就是您将帖子添加到您获取数据快照的数组的位置。
    • let dbRef = Database.database().reference().child("posts").child(nearbyPosts) 导致错误:“无法将 '[String]' 类型的值转换为预期参数类型 'String'" 还尝试使用 .child("(nearbyPosts)") 和 .child("posts/nearbyPosts") ,但这些结果会导致错误且没有任何解释。我忘了告诉我不需要“cmets”部分。我想要整个帖子。
    • 您是否忘记了 .child(nearbyPosts) 中的引号。 Idk 如果这是一个错字,但我想我不妨指出它。此外,您将“nearbyPosts”作为数据库中的内容进行引用。如果它不是来自数据库的东西,我会删除 .child(nearbyPosts) 因为它不在数据库中。
    猜你喜欢
    • 1970-01-01
    • 2018-07-17
    • 2017-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多