简体   繁体   English

如何使用Swift 5从Firebase中保存快照中的数据?

[英]How can I save the data from a snapshot from Firebase using Swift 5?

I am trying to save the data that I get from a snapshot into different variables. 我正在尝试将从快照中获取的数据保存到不同的变量中。

I have a class called QuotesModel and it has the QuoteID and the Quote as string variables. 我有一个称为QuotesModel的类,它具有QuoteID和Quote作为字符串变量。 I am trying to save off the snapshot of a quote to the Quote variable in that class. 我试图将报价的快照保存到该类中的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)
}

Let's clean this up and make is Swifty as well. 让我们清理一下,使它也是Swifty。

First define your class and array. 首先定义您的类和数组。 We are going to add logic to the class to 'break down' the snapshot into it's components and add some error checking in case the quote is nil. 我们将向该类添加逻辑以将快照“分解”到其组件中,并在引号为nil的情况下添加一些错误检查。

class QuoteModel {
    var quoteID = ""
    var quote = ""

    init(withSnapshot: DataSnapshot) {
        self.quoteId = withSnapshot.key
        self.quote = withSnapshot.value as? String ?? "No Quote"
    }
}

then a reference to our root database and an array. 然后是对我们的根数据库和数组的引用。 Note that it's generally best practice to refer to class vars with 'self.' 请注意,通常最好的做法是使用“ self”来引用类var。 and also lower case is typically used for vars, upper case for class definitions. 小写字母通常用于vars,大写字母用于类定义。

var rootref: DatabaseReference?
var quotesArr = [QuoteModel]()

And then the code to iterate over all quotes and populate the array 然后代码遍历所有引号并填充数组

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM