简体   繁体   中英

Upload array of Objects Firestore swift

ich work with swift and firestore and try to implemented a server similar to this:

    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

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. Converting the struct to a dictionary with type [String: Any] will ommit this error -

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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