简体   繁体   中英

Swift Retrieve Firebase Data from Database

I'm trying to retrieve data from Firebase but I'm having issues.

let refEmployees = Database.database().reference(withPath: "Employees")

    refEmployees.child("Logan").observeSingleEvent(of: .value, with: {
        snapshot in

        let shift = snapshot.value as? String
        self.shifts.append(shift!)
        self.workSchedule.reloadData()
    })

That is my code, my database looks like this .

When I run it, I get

fatal error: unexpectedly found nil while unwrapping an Optional value

Any ideas? I'm stumped. I also can add information to the database at the same time and change to childAdded and the information loads properly.

Usually I never try to get the reference "withPath", but by child. I would Try to do it like this:

let ref = Database.database().reference().child("Employees").child("Logan")

On the other part, is a bad practice to force unwrap optionals that you don't know you are actually going to get, I would change the closure to:

ref.observeSingleEvent(of: .value, with: {
    snapshot in

    guard let shift = snapshot.value as? String else {
        print("Value is Nil or not String")
        return
    }
    self.shifts.append(shift)
    self.workSchedule.reloadData()
})

Like someone in the comments said, may be a good idea to print the optional value first to see if you are actually getting the value that you need from the database.

Hope this helps

let refEmployees = Data`base.database().reference()

refEmployees,child("Employees").child("Logan").observeSingleEvent(of: .value, with: {
    snapshot in

    let shift = snapshot.value! as! [String : AnyObject]

    let dictKeys = [String](snapshot.keys)
//Will give you all` keys from DB 0,1,2,3,4,5,6

    let dictValues = [AnyObject](snapshot.values)
//will give you` all values "off", "off", "2-10"..."off"
//use keys or values append in array if you want as I could not understand what you are trying to save in self.shifts

    self.shifts.append(shift!)
    self.workSchedule.reloadData()
})

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