I have a very small chat in my app. whenever a user receives a message, the server sends a notification. In appDelegate I have implemented the code below:
@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler(.alert)
// print(UNNotificationAction)
print("📲📲📲 recieved")
if notification.request.content.title.contains("Message")
{
print("sub")
print(notification.request.content.subtitle)
print("body")
print(notification.request.content.body)
print("it containt DM ⏰")
let storyboard:UIStoryboard = UIStoryboard(name:"Chat", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: "chatRoomVc") as! ChatRoomViewController
vc.becomeFirstResponder()
vc.setRefreshListener {
print("triggered")
}
}
}
and whenever it runs, it calls the API and gets the chat data. the code below shows how it gets the data:
func setRefreshListener(listener:@escaping ()->Void){
refreshListener = listener
presenter.getttingChatRoomData(aptId: UserDefaults.standard.string(forKey: userAPTID)!, id: UserDefaults.standard.string(forKey: userID)!)
presenter.attachView(view: self)
super.loadView()
super.reloadInputViews()
tableView.reloadData()
}
in addition, I can get the data properly.
THE PROBLEM is it does not reload the data for the table view!!
does anybody has any solution why this is happening?
UPDATE: the code below runs when data is recieved:
func gettingUserChatWithSUCCESS(responce: [chatRomModel]) {
print("✅ getting chat room data SUCCESS")
data = responce
tableView.reloadData()
}
You can solve this issue using notification observer, Like follow this code.
Add notification observer in your viewcontroller
NotificationCenter.default.addObserver(self, selector: #selector(onReceiveData(_:)), name: "ReceiveData", object: nil)
@objc func onReceiveData(_ notification:Notification) {
// Do something now //reload tableview
}
call observer using this code in your appDelegate.swift
file receive notification method
NotificationCenter.default.post(name: Notification.Name("ReceiveData"), object: nil)
Note:- Remove notification observer when your viewcontrller will Disappear, using this code
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
NotificationCenter.default.removeObserver(self, name: "ReceiveData", object: nil)
}