我有一个我要保存到Firebase的结构。我想在Firebase中添加/创建一个结构列表。我该如何做,并能够检索按分数属性排序的这些项目的n
?
struct HighScoreItem {
var username: String = ""
var score: Int = 0
var date: Date = Date()
}
答案 0 :(得分:3)
我认为你必须将你的结构包装为属性列表。
首先添加一个函数,用于将结构转换为属性列表,如下所示:
struct HighScoreItem {
var username: String = ""
var score: Int = 0
var date: Date = Date()
init(from dictionary: [String: Any]) {
username = dictionary["username"] as! String
score = dictionary["score"] as! Int
date = dictionary["date"] as! Date
}
func asPropertyList() -> [String: Any] {
return ["username": username, "score": score, "date", date]
}
}
稍后您要将其上传到firebase:
let ref = Database.database().reference()
let highScore = HighScoreItem()
ref.child("HighScores").child("0").setValue(highScore.asPropertyList())
并阅读值
ref.child("HighScores").child("0").observeSingleEvent(of: .value, with: { (snapshot) in
// Get user value
let value = snapshot.value as? Dictionary
let highScore = HighScoreItem.init(from: value)
print(highScore)
// ...
}) { (error) in
print(error.localizedDescription)
}