Search code examples
swiftfirebasefirebase-realtime-databaseios11

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?


Solution

  • Your ref variable should be

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