ios - 使用 Swift 在 Firebase 中读取快照中的数组

标签 ios swift firebase firebase-realtime-database

在尝试读取这种形式的数组时需要帮助:

Firebase db

据我所知,我得到了这个

let defaults = UserDefaults.standard
let userUuid = defaults.string(forKey: defaultsKeys.keyOne)
let ref = FIRDatabase.database().reference().child("images").child("\(userUuid!)")
let filterQuery = ref.queryOrdered(byChild: "uuid").queryEqual(toValue: "\(uuid)") // where uuid is a value from another view

filterQuery.observe(.value, with: { (snapshot) in
        for images in snapshot.children {
            print(images)
        }
})

但我什么也没收到。我想读取图像的链接以在 View Controller 中显示它们。

最佳答案

  1. 确保下面行中的 uuid var 不是可选值(或者如果是,请将其解包),否则您将查询与 进行比较“可选(myUuidValue)” 而不是 “myUuidValue”

    let filterQuery = ref.queryOrdered(byChild: "uuid").queryEqual(toValue: "\(uuid)")
    
  2. 下面一行中的 snapshot 不仅包含图像,它还包含该 uuid 下的所有其他子项

    filterQuery.observe(.value, with: { (snapshot) in })
    

    所以像这样提取图像:

    filterQuery.observe(.value, with: { (snapshot) in
         let retrievedDict = snapshot.value as! NSDictionary
         let innerDict = retrievedDict["KeyHere"] as! NSDictionary  // the key is the second inner child from images (3172FDE4-...)
         let imagesOuterArray = userDict["images"] as! NSArray
         for i in 0 ..< imagesOuterArray.count {
               let innerArray = imagesOuterArray[i] as! NSArray
    
               for image in innerArray {
                    print(image as! String)
               }
         }
    })
    

    说明:将 uuid 的所有子项转换为 NSDictionary,然后使用这两个 for 循环提取嵌套数组

更新 感谢周杰伦指出错误!此外,正如 Jay 所建议的那样,考虑重组您的数据库并将这些数组替换为字典,这些字典可能包含每个图像的 URL、路径(如果需要,用于删除目的)和时间戳。

关于ios - 使用 Swift 在 Firebase 中读取快照中的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41477383/

相关文章:

java - 我想添加实时 Firebase 数据库中的值

ios - 获得正确 reuseIdentifier 的问题

ios - 如何在 Firebase 快照的控制流中使用 Nil? ( swift )

ios - 使用文档选择器从 iCloud 中选择一个文件夹

ios - 在 swift 4.2 中发送到实例的无法识别的选择器

ios - Swift 替换子字符串正则表达式

ios - KVO 在 iOS 9.3 中损坏

swift - 如何使用 Realm 浏览器创建新的 Realm 实例

android - 错误 : Failed to resolve: com. google.firebase :firebase-crash:17. 2.2

javascript - Firebase 函数 - 写入数据库