首页 > 解决方案 > 应用程序将数据重置为零,即使它存储在 firebase

问题描述

我有一个应用程序,它基本上是一个计算器,供用户计算他们从某些游戏中赢得的总金额。当我输入一个不是整数的数字时 - 例如“$ 1.25”,它在firebase上保存为“$ 1.25”,但是当我关闭应用程序并重新打开时,该值会重置为$ 0.00,但在firebase上仍然存储为$ 1.25”。如果我对一个整数做同样的事情——例如“$1”,然后关闭应用程序并打开,“$1”会留在应用程序上。

//add local data
        let gameKey = gameNames[addWinningsView.tag]
        let newValue = amountList[addWinningsView.tag] + (Double(addWinningsAmount.text!) ?? 0)
        UserDefaults.standard.set(newValue, forKey: gameKey)
        UserDefaults.standard.synchronize()

        //Update UI
        loadTotalAmount()

        //update to firebase
         let uuid = UIDevice.current.identifierForVendor!.uuidString
        let ref = Database.database().reference().child("app_data/user_total_won/\(uuid)/\(gameKey)")
        ref.setValue(newValue)

从 firebase 加载数据的代码

//Load winning points
        let uuid = UIDevice.current.identifierForVendor!.uuidString
        Database.database().reference().child("app_data/user_total_won/\(uuid)").observeSingleEvent(of: .value, with: {(snapshot) in
            let dict = snapshot.value as? [String : AnyObject] ?? [:]

            for game in gameNames {
                let amount = dict[game] as? Int ?? 0
                UserDefaults.standard.set(amount, forKey: game)
                UserDefaults.standard.synchronize()
            }
            self.loadTotalAmount()
        }

预期结果:从 Firebase 中检索不仅仅是一个整数的数据。

标签: iosswiftfirebasefirebase-realtime-database

解决方案


当您从 Firebase 检索值时,可选转换它,这样您就as? Double不会Int只获得整数。

要解决此问题,请更改let amount = dict[game] as? Int ?? 0let amount = dict[game] as? Double ?? 0是否将金额另存为DoubleFirestore。


推荐阅读