Firestore:如何从IOS(Swift)中的firestore获取对象数据并在tableview中显示它

时间:2018-06-02 04:48:32

标签: ios swift firebase google-cloud-firestore

我在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)

        }
    }

当我执行此代码时,它对else条件文件不存在但在firestore中它包含文档。要获得这些,还有其他方法可以解决enter image description here

enter image description here

1 个答案:

答案 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)
    }