【问题标题】:Firebase iOS Swift retrive list of favourites with data from other nodeFirebase iOS Swift 使用来自其他节点的数据检索收藏夹列表
【发布时间】:2017-04-23 12:47:08
【问题描述】:
Pictures
-pictureID
-- name
-- date

Like
-pictureID
-- userID: true
-- userID: true

likePerUser
-userID
--pictureID: true
--pictureID: true

Users
-userID
-- name
-- lastname

我想检索当前用户喜欢的所有图片。

我做到了:

          ref.child("likePerUser").child(FIRAuth.auth()!.currentUser!.uid).observeSingleEvent(of: .value, with: { (snap) in

      for item1 in snap.children{

      let firstItem1 = (snap: item1 as! FIRDataSnapshot)
          print("key favourites\(firstItem1.key)")

           let firstId = firstItem1.key


   self.ref.child("pictures").child(firstId).observeSingleEvent(of: .value, with: { (snapshot) in



    for item in snapshot.children{

      let firstItem = (snapshot: item as! FIRDataSnapshot)
      print("key pictures \(firstItem.key)")
               let dict = firstItem.value as! [String: Any
                   let name = dict["name"] as! String 
 print(name)

    }

即使,如果似乎 firstId 每次都有正确的值, 我总是得到一个错误:

无法将“__NSCFBoolean”(0x110dae5b8) 类型的值转换为 'NSDictionary' (0x110daf288)。

请帮忙....

【问题讨论】:

  • 如果您想获得帮助,请修复您的代码并告诉我们错误发生在哪里。

标签: ios swift firebase firebase-realtime-database


【解决方案1】:

我解决了这个问题:

if let dictionary = snapshot.value as? NSDictionary {

            if let name = dictionary["nome"] as? String {
                print(name)
            }
}

这个问题帮助了我:Swift - Could not cast value of type '__NSCFString' to 'NSDictionary'

我也不需要再次迭代。

【讨论】:

    【解决方案2】:
    let dict = firstItem.value as! [String: Any
    

    这里是您尝试将值转换为字典的地方。目前尚不清楚该值是否是基于您共享的数据库模型的字典。但是很有可能,如果您打印 firstItem.value.debugDescription,您将看到它的值不是字典对象。

    【讨论】:

    • 谢谢答案,如果我打印你的建议我得到:可选(名称)可选(日期)我喜欢的每张照片,所以我看到它不是字典,但我怎样才能访问那些如果我不能迭代字典,价值?
    • 如果您更新问题以显示更完整的数据库模型,这将对我有所帮助。例如,您的数据库模型没有显示一个名为“favperuser”的孩子,但您在代码中使用了一个。无论如何,请检查您的代码的大小写和拼写,以确保它与数据库中的路径名称完全匹配。
    猜你喜欢
    • 2018-10-02
    • 2020-04-22
    • 2018-09-04
    • 2021-03-08
    • 1970-01-01
    • 1970-01-01
    • 2016-08-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多