我正在尝试将 Firebase 用户名保存到 UserDefault。这是我所拥有的:
let databaseRef = FIRDatabase.database().reference()
databaseRef.child("Users").child((FIRAuth.auth()?.currentUser?.uid)!).observe(.value, with: { (snapshot) in
print("log in 4")
print(snapshot.value)
if snapshot.value != nil {
print("log in 4.1")
UserDefaults.standard.set(snapshot.value!["username"], forKey: "username")//Crash probably occurs here
print("log in 4.2")
}
})
系统打印log in 4
和log in 4.1
,但不是4.2。错误必须发生在两者之间的线上。我检查 snapshot.value
不是 nil,但它仍然打印 nil。我该如何解决这个问题?谢谢!
最佳答案
您当前只是检查 snapshot.value
是否包含 any 值,因此不是 nil
。但这并不意味着 snapshot.value
包含值 "username"
。
如果初始化为空,则它也不是 nil。
因此,要检查这个特定的 key ,您必须添加对 key 本身的检查:
if let userValue = snapshot.value?["username"]
关于ios - 检查nil后意外发现nil,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38647826/