【发布时间】:2017-02-20 18:25:34
【问题描述】:
我有一个从 Firebase 获取数据的函数。功能是:
private var levelsArr = [Level]()
func fetchLevels() {
DataService.instance.levelsRef.observe(.value, with: { (snapshot) in
print(snapshot)
if let lvlsDict = snapshot.value as? Dictionary<String, AnyObject> {
for(_, valueLvl) in lvlsDict {
if let lvlDict = valueLvl as? Dictionary<String, AnyObject> {
if let lvlId = lvlDict["id"] as? Int, let lvlCoverImg = lvlDict["coverImage"] as? String, let lvlTitle = lvlDict["title"] as? String {
let level = Level(id: lvlId, coverImage: lvlCoverImg, title: lvlTitle)
self.levelsArr.append(level)
print(self.levelsArr)
DispatchQueue.main.async(execute: {
self.collectionView?.reloadData()
})
}
}
}
}
})
print(self.levelsArr)
}
当我运行应用程序时,控制台会给我这个:
[Repeat.Level(id: 0, coverImage: "lvl0", title: "Level0")]
[Repeat.Level(id: 0, coverImage: "lvl0", title: "Level0"), Repeat.Level(id: 2, coverImage: "lvl2", title: "Level2")]
[Repeat.Level(id: 0, coverImage: "lvl0", title: "Level0"), Repeat.Level(id: 2, coverImage: "lvl2", title: "Level2"), Repeat.Level(id: 3, coverImage: "lvl3", title: "Level3")]
[Repeat.Level(id: 0, coverImage: "lvl0", title: "Level0"), Repeat.Level(id: 2, coverImage: "lvl2", title: "Level2"), Repeat.Level(id: 3, coverImage: "lvl3", title: "Level3"), Repeat.Level(id: 1, coverImage: "lvl1", title: "Level1")]
当我打印快照时,它是有序的,但是当我获取数据并将每个级别放入一个数组时,它不再是有序的。
为什么要这样做,我怎样才能让我的数据像在快照中一样排序?
谢谢。
更新
进行以下更改:
func fetchLevels() {
DataService.instance.levelsRef.queryOrdered(byChild: "lvlId").observe(.value, with: { (snapshot) in
print(snapshot)
if let lvlsDict = snapshot.value as? Dictionary<String, AnyObject> {
self.levelsArr.removeAll()
for(_, valueLvl) in lvlsDict {
if let lvlDict = valueLvl as? Dictionary<String, AnyObject> {
if let lvlId = lvlDict["id"] as? Int, let lvlCoverImg = lvlDict["coverImage"] as? String, let lvlTitle = lvlDict["title"] as? String {
let level = Level(id: lvlId, coverImage: lvlCoverImg, title: lvlTitle)
self.levelsArr.append(level)
DispatchQueue.main.async(execute: {
self.collectionView?.reloadData()
})
}
}
}
}
})
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
// Configure the cell
let lvlCell = collectionView.dequeueReusableCell(withReuseIdentifier: lvlCellId, for: indexPath) as! lvlCell
levelsReverseArr = levelsArr.reversed()
print(levelsReverseArr)
lvlCell.level = levelsReverseArr[indexPath.item]
return lvlCell
}
控制台结果:
Snap (levels) {
level0 = {
coverImage = lvl1;
id = 0;
title = Level1;
};
level1 = {
coverImage = lvl2;
id = 1;
title = Level2;
};
level2 = {
coverImage = lvl3;
id = 2;
title = Level3;
};
[Repeat.Level(id: 1, coverImage: "lvl1", title: "Level1"), Repeat.Level(id: 3, coverImage: "lvl3", title: "Level3"), Repeat.Level(id: 2, coverImage: "lvl2", title: "Level2"), Repeat.Level(id: 0, coverImage: "lvl0", title: "Level0")]
【问题讨论】:
标签: ios swift firebase firebase-realtime-database