簡體   English   中英

使用Swift在Firebase中讀取快照中的數組

[英]Read array inside snapshot in Firebase with Swift

需要幫助來嘗試讀取這種形式的數組:

Firebase數據庫

據我嘗試,我得到了

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)
        }
})

但是我什么也沒收到。 我想閱讀圖像的鏈接以在視圖控制器中顯示它們。

  1. 確保下面一行中的uuid var不是一個可選值(如果是,請解開它),因為否則,您將查詢比較"Optional(myUuidValue)"而不是"myUuidValue"

     let filterQuery = ref.queryOrdered(byChild: "uuid").queryEqual(toValue: "\\(uuid)") 
  2. snapshot行中的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,路徑(如果需要的話,用於刪除)和每個圖像的時間戳的字典替換這些數組。

努力尋找答案后,此代碼有效

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()
                    }


                }
            }
        }

    })

我可以收到有關此問題的反饋嗎?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM