PerNil
PerNil

Reputation: 187

Finding nil when reading from database

When trying to read from Firebase I get

Fatal error: Unexpectedly found nil while unwrapping an Optional value

Code for reading the database:

ref = Database.database().reference().child("userDatabases").child(userID!).child("-Lk__eup2Z7WR-iqtXkI").child("-Lk__gmhOTWfVzEPVo2t")    

    ref?.observeSingleEvent(of: .value, with: { (snapshot) in
                for child in snapshot.children.allObjects as! [DataSnapshot] {

                  let dict = child.value as? [String : AnyObject] ?? [:]

                    self.objectProducer.append(dict["objectProducer"] as! String)
                    self.objectType.append(dict["objectType"] as! String)
                    self.objectAmount.append(dict["amount"] as! String)
                    self.objectMeasureUnit.append(dict["unit"] as! String)
                }
            })

If I try to print for example: print(dict["objectProducer"]) I get the correct result.

The FirebaseStructure I´m trying to read from looks like this:

 "-Lk__eup2Z7WR-iqtXkI" : {
          "-Lk__gmhOTWfVzEPVo2t" : {
            "5740700998485" : {
              "amount" : "330",
              "objectProducer" : "Coca Cola",
              "objectType" : "Zero",
              "unit" : "Milliliter"
            },
            "createdOn" : "24-7-2019 at: 22:5:35",
            "listID" : "-Lk__gmhOTWfVzEPVo2t",
            "name" : "Test"
          },    

What is going wrong here?

Upvotes: 1

Views: 64

Answers (2)

CAGRI COLAK
CAGRI COLAK

Reputation: 56

in my opinion, change this line of code

let dict = child.value as? [String : AnyObject] ?? [:]

to:

guard let dict = child.value as? [String: AnyObject] else { return }

then you sould not getting error.

hop this help.

Upvotes: 1

Hoang Nguyen Chi
Hoang Nguyen Chi

Reputation: 171

I think the crash due to self.objectAmount.append(dict["amount"] as! String). You try execute the code: self.objectAmount.append(dict["amount"] as! Int)

Upvotes: 0

Related Questions