简体   繁体   中英

How do I fetch data from firebase?

I am new to swift and I am trying to do as best as I can not to bother others I have looked for days to solve a problem but still hopeless, I hope you guys could tell me how can I fix it.

I want to get data and to put it in newPerson enter code here newPersons.append(nyPerson!) and it crashes saying Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value

Auth.auth().addStateDidChangeListener { (auth, user) in
            self.ref = Database.database().reference(withPath: "personer")
            self.ref.observe(.value, with: { (snapshot) in
                var newPersons:[BackUp] = []
                for item in snapshot.children {
                    let nyPerson = BackUp(snapshot: item as! DataSnapshot)
                    newPersons.append(nyPerson!)

                }
                self.personsArray = newPersons
                self.tableView.reloadData()
            })
        }

This is a code form Getting Started documentation: https://firebase.google.com/docs/database/ios/lists-of-data

I think the issue you have in BackUp.init(snapshot: DataSnapshot). be sure to get data with as optional, for example:

init(snapshot: DataSnapshot) {
 let value = snapshot.value as? NSDictionary
 let username = value?["username"] as? String ?? ""
 ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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