【问题标题】:Update an existing item in a ChatModel dictionary from a Firestore snapshot从 Firestore 快照更新 ChatModel 字典中的现有项目
【发布时间】:2020-05-13 21:37:08
【问题描述】:

我想在 TableView 中显示特定用户的所有现有聊天(姓名、LastMessage)的概览。

现在,我在 TableView 中添加了一个新项目,这显然是错误的,我想通过它的键“ChatId”来更新现有项目

这是我的模特:

class ChatModel {

var chatOwnerId: String?
var chatPartnerId: String?
var createdDate: Timestamp?
var chatId: String?
var lastMessage: String?
var lastMessageDate: Timestamp?

init(dictionary: [String: Any]) {
    chatOwnerId = dictionary["chatOwnerId"] as? String
    chatPartnerId = dictionary["chatPartnerId"] as? String
    createdDate = dictionary["createdDate"] as? Timestamp
    chatId = dictionary["chatId"] as? String
    lastMessage = dictionary["lastMessage"] as? String
    lastMessageDate = dictionary["lastMessageDate"] as? Timestamp
    }
}

我如何将数据添加到我的模型中:

func loadChatOverviewNew(currentUser: String) {
    ChatApi.shared.observeChatOverviewNew(currentUser: currentUser) { (chatOverview) in
        self.chats.insert(chatOverview, at: 0)            
        self.chatTableView.reloadData()
    }
}

当我收到新快照时如何更新我的“聊天”,而不是追加/插入它?

【问题讨论】:

    标签: swift google-cloud-firestore


    【解决方案1】:

    要更新现有项目,请通过调用 `` 在数组中找到该项目,然后对其进行更新。

    类似:

    
    ChatApi.shared.observeChatOverviewNew(currentUser: currentUser) { (chatOverview) in
        if let index = self.chats.firstIndex(where: { $0.chatId == chatOverview.chatId }) {
            self.chats[index] = chatOverview
        }
        else {
            self.chats.insert(chatOverview, at: 0)            
        }
        self.chatTableView.reloadData()
    }
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-05-13
      • 2019-02-08
      • 2021-09-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-17
      相关资源
      最近更新 更多