我正在尝试将从快照中获取的数据保存到不同的变量中。
我有一个名为 QuotesModel 的类,它具有作为字符串变量的 QuoteID 和 Quote。我正在尝试将报价的快照保存到该类中的 Quote 变量。
class QuotesModel:NSObject {
var QuoteID:String = ""
var quote:String = ""
}
var rootref: DatabaseReference?
var QuotesArr = [QuotesModel]()
override func viewDidLoad() {
rootref = Database.database().reference()
let ref = rootref!.child("HelloWorld")
super.viewDidLoad()
ref.observe(.childAdded, with: {(snapshot) in
print(snapshot)
guard let dictionary = snapshot.value as? [String : AnyObject]
else {
return
}
let Obj = QuotesModel()
Obj.QuoteID = snapshot.key
Obj.quote = (dictionary["Test1"] as? String)!
self.QuotesArr.append(Obj)
}, withCancel: nil)
}
最佳答案
让我们把它清理干净,然后 make 也是 Swifty。
首先定义你的类和数组。我们将向类添加逻辑以将快照“分解”为其组件,并添加一些错误检查以防引用为 nil。
class QuoteModel {
var quoteID = ""
var quote = ""
init(withSnapshot: DataSnapshot) {
self.quoteId = withSnapshot.key
self.quote = withSnapshot.value as? String ?? "No Quote"
}
}
然后是对我们的根数据库和数组的引用。请注意,通常最佳做法是使用“self”来引用类变量。并且小写通常用于变量,大写用于类定义。
var rootref: DatabaseReference?
var quotesArr = [QuoteModel]()
然后是遍历所有引号并填充数组的代码
func iterateOverAllQuotes() {
self.rootref = Database.database().reference()
let ref = self.rootref!.child("HelloWorld")
super.viewDidLoad()
ref.observe(.childAdded, with: { snapshot in
let aQuote = QuoteModel(withSnapshot: snapshot)
self.quotesArr.append(aQuote)
})
}
关于ios - 如何使用 Swift 5 从 Firebase 的快照中保存数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57021836/