-2

直到最近,我从数据库中提取数据都没有问题 - 只有当我决定添加另一个变量(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"
4

1 回答 1

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)")
})
于 2017-05-07T21:47:19.247 回答