直到最近,我还没有问题能够从数据库中提取数据 - 并且只有在我决定添加另一个变量(totalDistance)时它才会开始中断,但是在尝试删除这个新编写的代码时,错误仍然存在。
fatal error: unexpectedly found nil while unwrapping an Optional value
(lldb)
当我尝试进入导致错误的“个人资料”页面时,这是我得到的错误,这里是我写的能够写标签的函数 -
let ref = FIRDatabase.database().reference()
let UserID = FIRAuth.auth()?.currentUser?.uid
ref.child("user").child(UserID!).observeSingleEvent(of: .value, with: { (snapshot) in
let value = snapshot.value as? NSDictionary
let displayname = value?["nickname"] as? String ?? "Nickname Missing"
let bronzeMedals = value?["bronzeMedals"] as? String ?? "no bronze in db"
let silverMedals = value?["silverMedals"] as? String ?? "no silver in db"
let goldMedals = value?["goldMedals"] as? String ?? "no gold in db"
let totalDistance = value?["totalDistance"] as? String ?? "no total in db"
print(bronzeMedals, silverMedals, goldMedals)
self.displaynameLabel.text = ("Username: \(displayname)")
self.goldmedalsLabel.text = ("Gold medals: \(goldMedals)")
self.silvermedalsLabel.text = ("Silver medals: \(silverMedals)")
self.bronzemedalsLabel.text = ("Bronze medals: \(bronzeMedals)")
self.totaldistanceLabel.text = ("Total distance: \(totalDistance)")
})
这种调用信息的方法已经完美无缺,直到我试图添加另一个变量,我对此错误感到非常困惑,似乎无法找到解决方法 - 无论我查找多少不同的错误已经得到了回答,所以任何信息都将非常重要并且非常受欢迎。
这是用户的数据库文件 - 正在调用
age:
"18"
bronzeMedals:
"2"
goldMedals:
"3"
nickname:
"Test Account"
silverMedals:
"5"
totalDistance:
"2"
答案 0 :(得分:0)
您确实需要更改代码,以便不使用选项。
let ref = FIRDatabase.database().reference()
guard let user = FIRAuth.auth()?.currentUser else { return }
ref.child("user").child(user.uid).observeSingleEvent(of: .value, with: { (snapshot) in
guard let value = snapshot.value as? Dictionary<String,String> else { return }
let displayname = value["nickname"] ?? "Nickname Missing"
let bronzeMedals = value["bronzeMedals"] ?? "no bronze in db"
let silverMedals = value["silverMedals"] ?? "no silver in db"
let goldMedals = value["goldMedals"] ?? "no gold in db"
let totalDistance = value["totalDistance"] ?? "no total in db"
// Update Labels
self.displaynameLabel.text = ("Username: \(displayname)")
self.goldmedalsLabel.text = ("Gold medals: \(goldMedals)")
self.silvermedalsLabel.text = ("Silver medals: \(silverMedals)")
self.bronzemedalsLabel.text = ("Bronze medals: \(bronzeMedals)")
self.totaldistanceLabel.text = ("Total distance: \(totalDistance)")
})