Firebase循环嵌套数据并存储在数组中

时间:2017-05-29 07:50:03

标签: ios swift firebase firebase-realtime-database uicollectionview

我试图将图片网址列表保存到一个空的字符串数组中,然后显示在集合视图中。我无法循环浏览字典来存储网址。

我在EncounterTableViewController.swift中获取Firebase数据 ,然后有另一个详细的视图控制器EncounterDetailViewController.swift有一个EncounterCollectionViewCell.swift

Encounter.swift

class Encounter {
    ...
    ...
    var images: [String] = []
}

EncounterTableViewController.swift

func showAllEncounters() {
    // Firebase tableview data
    FIRDatabase.database().reference().child("encounters").observeSingleEvent(of: .value, with: { (snapshot) in
        for rest in snapshot.children.allObjects as! [FIRDataSnapshot] {
            guard let restDict = rest.value as? [String: Any] else { continue }

            let encounter = Encounter()
            ...
            ...
            let mediaDict = restDict["media"] as! [[String:Any]]

            // need to find nested images and set them to encounter.images here

            self.encounters.append(encounter)

            self.tableView.reloadData()
        }
    })
}

EncounterDetailViewController.swift

private let reuseIdentifier = "imageCell"

class EncounterDetailViewController: UIViewController, 
UICollectionViewDataSource, UICollectionViewDelegate {

// MARK: - Properties
var selectedEncounter: Encounter?

// MARK: - View did load
override func viewDidLoad() {
    super.viewDidLoad()

}

    // MARK: - UICollectionViewDataSource
func numberOfSections(in collectionView: UICollectionView) -> Int {
    return 1
}

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return (selectedEncounter?.images.count)!
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! EncounterCollectionViewCell

    cell.imageView.sd_setImage(with: URL(string: (selectedEncounter?.images[indexPath.row])!))

    return cell
}

遇到数据结构

encounters
  -12
    -name: "shark"
    -length: "3"
    -media
      -0
        -id: "3242"
        -url: "http://google.com"
        -thumb-url: "http://thisurl.com"
      -1
        -id: "4252"
        -url: "http://google.com"
        -thumb-url: "http://thisurl.com"

1 个答案:

答案 0 :(得分:2)

而不是if (string1.toUpperCase(Locale.GERMAN).equals(string2.toUpperCase(Locale.GERMAN))) ,最简单的解决方案是使用flatMap

for loop

这个单行解决方案会减少let mediaDict = restDict["media"] as! [[String:Any]] images = mediaDict.flatMap { $0["thumb_url"] as? String } 的代码,但如果仍想使用循环,那么你就可以这样做。

for loop