简体   繁体   English

上传对象 Firestore 数组 swift

[英]Upload array of Objects Firestore swift

ich work with swift and firestore and try to implemented a server similar to this:我与 swift 和 firestore 一起工作,并尝试实现与此类似的服务器:

    chatId: String
    eventCreatorId: String
    matchedUserId: String
    eventId: String
    messages: [
    {userId: String, timestamp:timestamp, messageText: String},
    {userId: String, timestamp:timestamp, messageText: String},
  ],

in other Words with a MVVM design i want to upload a array of Models but i getting a type error when i try with this换句话说,使用 MVVM 设计我想上传一个模型数组,但是当我尝试使用这个时出现类型错误

struct ChatModel: Codable {
    var chatId: String
    var eventCreatorId: String
    var matchedUserId: String
    var eventId: String
    var messages: [MessageModel]

}

struct MessageModel: Codable {
    var userId: String
    var timeStamp: Timestamp
    var messageText: String
    
}

the error happens if i try to upload如果我尝试上传会发生错误

    func uploadMessage(messageText: String, chatId: String) -> Promise<Void> {
        return Promise { seal in
            guard let currentUser = Auth.auth().currentUser else {
                return
            }
            let timeStamp: Timestamp = Timestamp(date: Date())
            let messageModel = MessageModel(userId: currentUser.uid,timestamp: timeStamp, messageText: messageText)
            print(messageModel)
                let _ = db.collection("chats")
                    .document(chatId)
                    .updateData(["messages" : FieldValue.arrayUnion([messageModel])]) { error in
                        if let error = error {
                            seal.reject(error)
                        } else {
                            seal.fulfill(())
                        }
                    }
            }
        }
        
    }

i tried also without the timestamp but ran into the same error我也试过没有时间戳但遇到了同样的错误

can someone explain me what am i doing wrong?有人可以解释一下我在做什么错吗?

On ArrayUnion, Firestore does not understand the type you're trying to pass.在 ArrayUnion 上,Firestore 不了解您要传递的类型。 Converting the struct to a dictionary with type [String: Any] will ommit this error -将结构转换为类型为 [String: Any] 的字典将忽略此错误 -

struct MessageModel: Codable {
    var userId: String
    var timeStamp: Timestamp
    var messageText: String
    
    var dictionary: [String: Any] {
        return["userId": userId,
               "timeStamp": timeStamp,
               "messageText": messageText]
    }
}

Then when you're uploading to Firestore you use the Dict value:然后,当您上传到 Firestore 时,您使用 Dict 值:

 .updateData(["messages" : FieldValue.arrayUnion([messageModel.dictionary])]) { error in

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM