如何使用swift将对象形式的数据存储到firestore中

如何使用swift将对象形式的数据存储到firestore中,swift,google-cloud-firestore,Swift,Google Cloud Firestore,我想用swift语言将数据存储成对象形式 collection/ document/ collection/ document1/: Invitess1(object) : name :"santosh" phone :1234567890 Invitee2(object) :

我想用swift语言将数据存储成对象形式

collection/
document/
collection/
document1/:
           Invitess1(object) :
                              name :"santosh"
                              phone :1234567890 
          Invitee2(object) :
                              name :"sam"
                              phone:1234654768
          .....
document 2/
          Initee1(object) :

                           name:"red"
                           phone:4654343532
         .......

可以这样存储数据吗?如果可能的话,怎么做?我试着这样做:

for var i in 0..<n { // n is no.of selected contacts
            for var j  in i...i {
                print("amount is \(d[i])")
                print("phone number is \(num[j])")
                let dataToSave:[String: Any] = ["name" :"vijayasri",
                                                "PhoneNumber":num[j],
                                                "Amount": d[i],
                                                ]
            }

        }
        var ref:DocumentReference? = nil
        ref = self.db.collection("deyaPayUsers").document("nothing").collection("Split").addDocument(data: dataToSave){
            error in
            if let error = error {
                print("error adding document:\(error.localizedDescription)")

            } else {
                print("Document ades with ID:\(ref!.documentID)" )
            }

        }


    }
对于0..中的var i,您的示例代码永远不会按预期工作,因为
dataToSave
j
循环的每次迭代中都会被覆盖。您的内部
j
循环可能在
i…i

要在一个文档中存储多个对象,请在Swift中创建包含多个对象的文档。既然您知道如何将对象编码为
[String:Any]
,只需将这些字典合并成一个更大的
[String:Any]
文档即可

我会将您的代码更改为:

var dataToSave: [String:Any] = []()
for var i in 0..<n { // n is no.of selected contacts
    var inProcess: [String:Any] = []()
    for var j  in i...i {
        print("amount is \(d[i])")
        print("phone number is \(num[j])")
        let detail: [String: Any] = ["name" :"vijayasri",
                                     "PhoneNumber":num[j],
                                     "Amount": d[i]]
        inProcess["NextKey\(j)"] = detail
     }
    dataToSave["SomeKey\(i)"] = inProcess
 }

 var ref:DocumentReference? = nil
 ref = self.db.collection("deyaPayUsers").document("nothing").collection("Split").addDocument(data: dataToSave){
        error in
        if let error = error {
            print("error adding document:\(error.localizedDescription)")

        } else {
            print("Document ades with ID:\(ref!.documentID)" )
        }

    }


}
var dataToSave:[String:Any]=[]()

对于0中的var i..要保存的数据格式不正确。根据您的图表,您的文档将需要存储一个对象数组,但您的示例不是数组。您的示例是单个对象。可以在ios中存储这样的数据吗?您共享的文档仅用于文档中的一个对象。但我希望将多个对象表单存储到单个文档中。字段值也是以动态方式而不是静态方式应用的。好的,它可以工作。它像我需要的那样储存着。我将inprocess(j)更改为inprocess(I)。