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

时间:2017-01-05 04:36:59

标签: 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)
        }
})

但我一无所获。我想阅读图像的链接以在视图控制器中显示它们。

2 个答案:

答案 0 :(得分:2)

  1. 确保下面一行中的uuid var不是可选值(或者如果是,请打开它),否则您将查询与"Optional(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循环提取嵌套数组

  3. <强>更新 感谢Jay指出错误!另外,正如Jay建议的那样,考虑重构数据库并用可能包含URL,路径(如果需要的话用于删除目的)的字典替换这些数组,以及每个图像的时间戳。

答案 1 :(得分:-1)

在找到答案之后,得到了这段代码

let ref = FIRDatabase.database().reference().child("images").child("\(userUuid!)")
    let filterQuery = ref.queryOrdered(byChild: "identifier").queryEqual(toValue: "\(identifier)")

    filterQuery.observe(.value, with: { (snapshot) in
        for child in snapshot.children {
            if (child as AnyObject).hasChild("images") {
                let images = (images as AnyObject).childSnapshot(forPath: "images").value! as! NSArray
                for i in images {
                    for j in i as! [AnyObject] {
                        let url = NSURL(string: j as! String)
                        //Then downloaded the images to show on view
                        URLSession.shared.dataTask(with: url! as URL, completionHandler: { (data, response, error) in
                            if error != nil {
                                print(error)
                                return
                            }
                            //Code to show images..

                        }).resume()
                    }


                }
            }
        }

    })

我可以收到有关此事的反馈吗?