ios - 应用程序将数据重置为零,即使它存储在 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 中检索不仅仅是一个整数的数据。
解决方案
当您从 Firebase 检索值时,可选转换它,这样您就as? Double
不会Int
只获得整数。
要解决此问题,请更改let amount = dict[game] as? Int ?? 0
为let amount = dict[game] as? Double ?? 0
是否将金额另存为Double
Firestore。
推荐阅读
- python - 如何获得图像的压缩
- reactjs - 如何从 Next.js 中的 WP REST API 获取响应标头?
- swift - 使用 Picker (SwiftUI) 从 CoreData 实体中选择并保存值
- powershell - 更改 IIS 会话到期
- java - 为什么当我尝试在 db 中插入新对象时出现错误?
- python - 嵌套在 elif 中的 elif 语法无效
- android - 如何将 Android File Picker 连接到内存中创建的 PDF 文档?
- javascript - react-beautiful-dnd draggables 拖动一切
- python - 在一个数据框中连接多个 CSV 文件
- reactjs - 如何在 React 中构建自定义表单