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

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)
}

我从 Firebase 教程中复制了代码,但得到了:"Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value"

如果我把代码改成:

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)
}

username 不打印。 我该如何解决?检索数据的最佳方式是什么?

你的 ref 变量应该是

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