Thomas Tseng
Thomas Tseng

Reputation: 53

Reading Firebase Data: Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value

import Firebase
import FirebaseAuth
import FirebaseDatabase

let userID = Auth.auth().currentUser?.uid
var ref: DatabaseReference!

ref.child("users").child(userID!).observeSingleEvent(of: .value, with: { (snapshot) in
  let value = snapshot.value as? NSDictionary
  let username = value?["username"] as? String ?? ""
  let user = User(username: username)
  print(username)
  }) { (error) in
    print(error.localizedDescription)
}

I copied the code from the Firebase tutorial but got: "Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value"

If I changed the code into:

ref?.child("users").child(userID!).observeSingleEvent(of: .value, with: { (snapshot) in
  let value = snapshot.value as? NSDictionary
  let username = value?["username"] as? String ?? ""
  let user = User(username: username)
  print(username)
  }) { (error) in
    print(error.localizedDescription)
}

The username doesn't print. How could I fix it? And what is the best way to retrieve data?

Upvotes: 1

Views: 635

Answers (1)

Elhoej
Elhoej

Reputation: 751

Your ref variable should be

var ref = Database.database().reference()

Upvotes: 3

Related Questions