我有一些数据存在于实时数据库. 但是当我获取数据时,它会给我错误。
我有这样的数据在实时数据库:
"Transaction_By_Date": {
"Ahmad_24-03-2023 17:38:15": {
"28-03-2023": {
"total_amount_receive": 10000,
"total_amount_send": 20000,
"transactions": {
"-NRZfbq2xYhHF-v1beKC": {
"amount": 20000,
"date": "28-03-2023 01:06:53",
"detail": "Sending",
"image": "no image",
"type": "Send"
},
"-NRZfs_i1RWHQ-8xYYa1": {
"amount": 10000,
"date": "28-03-2023 01:07:40",
"detail": "Detail",
"image": "no image",
"type": "Receive"
}
},
"29-03-2023": {
"total_amount_receive": 5000,
"total_amount_send": 0,
"transactions": {
"-NRZfxRoPkLQxOJfCyGq": {
"amount": 5000,
"date": "28-03-2023 01:08:24",
"detail": "Received",
"image": "no image",
"type": "Receive"
}
}
}
}
}
}
我曾尝试像这样使用firebasedatabasesswift获取此响应.我的代码是:
import FirebaseDatabase
import FirebaseDatabaseSwift
func getEntries(userId: String) {
Database.database().reference().child("Transaction_By_Date").child(userId).observe(.value) { snapshot in
guard let children = snapshot.children.allObjects as? [DataSnapshot] else {
return
}
let transactionsData = children.compactMap { dictionary in
do {
var transaction = try dictionary.data(as: TransactionByDate.self)
transaction.id = dictionary.ref.key
return transaction
} catch let error {
print(error.localizedDescription)
return TransactionByDate()
}
}
print(transactionsData)
}
}
这是我的TransactionByDate模型:struct TransactionByDate: Identifiable, Codable {
var id: String?
var total_amount_sent: Int?
var total_amount_receive: Int?
var transactions: [Transactions]?
}
struct Transactions: Identifiable, Codable {
var id: String?
var amount: Int?
var date: String?
var detail: String?
var image: String?
var type: String?
}
当这个函数被调用时。我得到这个错误:
谁能告诉我我做错了什么?我该怎么做才能让它起作用呢?数据无法读取,因为它不是正确的格式。
A Joakim指出,JSON中的transactions
节点是一个字典,而不是一个数组。当您在Firebase中通过调用childByAutoId
创建列表时,这是正常的。
要修复这个错误,声明你的transactions
属性为一个字典:
var transactions: [String: Transactions]?
了解更多关于为什么Firebase不使用数组的列表,我建议阅读最佳实践:数组在Firebase..