收到通知时刷新表视图

jac*_*ack 2 listener uitableview push-notification ios swift

我的应用程序中有一个非常小的聊天。每当用户收到消息时,服务器都会发送通知。在 appDelegate 中,我实现了以下代码:

@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")
            }

        }

    }
Run Code Online (Sandbox Code Playgroud)

每当它运行时,它都会调用 API 并获取聊天数据。下面的代码显示了它如何获取数据:

 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()


}
Run Code Online (Sandbox Code Playgroud)

此外,我可以正确获取数据。

问题是它不会重新加载表视图的数据!!

有没有人有任何解决方案,为什么会发生这种情况?

更新: 以下代码在收到数据时运行:

 func gettingUserChatWithSUCCESS(responce: [chatRomModel]) {
        print("? getting chat room data SUCCESS")
        data = responce
        tableView.reloadData()
    }
Run Code Online (Sandbox Code Playgroud)

Atu*_*mar 8

您可以使用通知观察器解决此问题,例如按照此代码。

在您的视图控制器中添加通知观察者

NotificationCenter.default.addObserver(self, selector: #selector(onReceiveData(_:)), name: "ReceiveData", object: nil)

@objc func onReceiveData(_ notification:Notification) {
    // Do something now //reload tableview
}
Run Code Online (Sandbox Code Playgroud)

在您的appDelegate.swift文件中使用此代码调用观察者接收通知方法

NotificationCenter.default.post(name: Notification.Name("ReceiveData"), object: nil)
Run Code Online (Sandbox Code Playgroud)

注意:- 当您的视图控制器消失时,使用此代码删除通知观察者

override func viewWillDisappear(_ animated: Bool) {
      super.viewWillDisappear(animated)
      NotificationCenter.default.removeObserver(self, name: "ReceiveData", object: nil)
}
Run Code Online (Sandbox Code Playgroud)