为了简要说明,我正在使用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上。任何人都可以指出任何建议,因为我已经坚持了一段时间。谢谢!
答案 0 :(得分:0)
您可以使用通知来观察和更新VC中的更改。
创建通知名称:
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()
}
在视图控制器上添加一个想要重新加载数据的观察者:
{{1}}