我在firestore数据库中有一个像对象形式的结构。我需要从firestore检索数据并在swb中的tablebview中显示它
-
collection//users
-authid
- collection//Split
- auth id
- collection//SentInvitations
-automatic id
-Invitee(i)(object)
.name:bnnn
.phonenumber:567788
.amount:123
- Invitee(2)
.name:aaaa
.phonenumber:987654321
.amount:198
其中i =被邀请者的号码 现在我需要检索这些所有被邀请者并显示到表格视图
代码我试图从firestore检索数据
func loadData(){
let authid = Auth.auth().currentUser?.uid
let docRef = db.collection("deyaPayUsers").document(authid!).collection("Split").document(authid!).collection("SentInvitations").document(senderautoid!)
docRef.getDocument { (document, error) in
if let city = document.flatMap({
$0.data().flatMap({ (data) in
return Invite(dictionary: data)
})
}) {
print("City: \(city)")
} else {
print("Document does not exist")
}
}
}
和我的模型类邀请
import Foundation
import FirebaseFirestore
protocol DocumentSerializable2
{
init?(dictionary:[String:Any])
}
struct Invite {
var PhoneNumber:Int
var Amount:Int
//var Status:String
var dictionary:[String:Any]{
return [
"PhoneNumber":PhoneNumber,
"Amount":Amount,
]
}
}
extension Invite : DocumentSerializable2{
init?(dictionary: [String:Any]){
guard let amount = dictionary["Amount"] as? Int,
let phonenumber = dictionary["PhoneNumber"] as? Int else { return nil}
self.init(PhoneNumber:phonenumber, Amount:amount)
}
}
答案 0 :(得分:0)
在与Vijju讨论问题后,我们错过了一点,即Firestore在其字典中没有使用Swift
类型,但Objective-C
类型。因此,预期为Int
的内容应首先投放到NSNumber
,然后从NSNumber
获得Int
值。所以总结一下代码:
init?(dictionary: [String:Any]){
guard let nsNumberAmount = dictionary["Amount"] as? NSNumber,
let nsNumberPhoneNumber = dictionary["PhoneNumber"] as? NSNumber else { return nil}
let phoneNumber = nsNumberPhoneNumber.intValue
let amount = nsNumberAmount.intValue
self.init(PhoneNumber:phonenumber, Amount:amount)
}