将来自另一个 VC 的消息添加到 JSQCollectionView:Swift

Adding messages to a JSQCollectionView from another VC: Swift

简而言之,我将 JSQMessagesViewController 用于基于聊天的应用程序。正常添加消息工作正常。现在开始讨论这个问题,我正在使用推送通知来接收消息并将它们存储到核心数据中。我坚持的是消息不会立即显示在聊天中。就像你刷新它们会显示但不是在那个确切的时刻。

代码如下:

AppDelegate:

func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (_ options: UNNotificationPresentationOptions) -> Void) {

    let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
    let messageVC = mainStoryboard.instantiateViewController(withIdentifier: "messageVC") as! messagesViewController

    if let incomingMessageSenderId = notification.request.content.userInfo["User_ID"] as? NSString {

        incomingMsgSenderId = String(incomingMessageSenderId)
    }
    if let message = notification.request.content.userInfo["Message"] as? String {

        msg = String(message)

    }

    DispatchQueue.main.async {

        messageVC.checkForMessages(id: incomingMsgSenderId)
    }

}

MessagesVC

func checkForMessages(id: String) {

    messages.removeAll()

    let context : NSManagedObjectContext = appDel.managedObjectContext

    let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Nd_conversation")

    request.returnsObjectsAsFaults = false

    request.predicate = NSPredicate(format: "to_user_id = %@", id)

    do {
        let results = try context.fetch(request)

        if results.count > 0 {

            for result in results as! [NSManagedObject] {

                let conversation_id = result.value(forKey: "id")

                    let request2 = NSFetchRequest<NSFetchRequestResult> (entityName: "Nd_chat")
                    request2.returnsObjectsAsFaults = false

                    request2.predicate = NSPredicate(format: "conversation_id = %@", conversation_id! as! CVarArg)

                    do {

                        let results2 = try context.fetch(request2)

                        if results2.count > 0 {
                            for result2 in results2 as! [NSManagedObject] {

                                if let body = result2.value(forKey: "message_body") as? String {


                                    loadedMessages.append(body)

                                    if let sender_id = result2.value(forKey: "sender_id") as? Int {

                                        let sent_id = String(sender_id)

                                        print("Sender id: \(sent_id)")

                                        senderIds.append(sender_id)

                                        self.addMessage(sent_id, text: body)
                                      self.finishSendingMessage(animated: true)

                                    }


                                }
                                else if let imageData = result2.value(forKey: "media_path") as? NSData{
                                    //photo

                                    let image = UIImage(data: imageData as Data)

                                    let photoItem = JSQPhotoMediaItem(image: image)

                                    if let sender_id = result2.value(forKey: "sender_id") as? Int {

                                        let photoMessage = JSQMessage(senderId: String(sender_id), displayName: self.senderDisplayName, media: photoItem)

                                        messages.append(photoMessage!)

                                        self.finishSendingMessage(animated: true)
                                    }
                                }
                            }
                        }
                    }
            }
        }

核心数据工作正常。甚至消息也会附加到消息数组中。问题出在self.finishSendingMessage。任何人都可以指出任何建议,因为我已经坚持了一段时间。谢谢!

您可以使用通知来观察和更新 VC 中的变化。

创建通知名称:

extension Notification.Name {
    static let reload = Notification.Name("reload")
}

您可以post通知使用:

NotificationCenter.default.post(name: .reload, object: nil)

并在要重新加载数据的视图控制器中添加一个观察者:

override func viewDidLoad() {
    super.viewDidLoad()
    NotificationCenter.default.addObserver(self, selector:#selector(reloadTableData(_:)), name: .reload, object: nil)
}

func reloadTableData(_ notification: Notification) {
    tableView.reloadData()
}