【问题标题】:refresh table view when notification is received收到通知时刷新表格视图
【发布时间】:2019-07-05 17:27:20
【问题描述】:

我的应用中有一个非常小的聊天。每当用户收到消息时,服务器都会发送通知。在 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")
            }

        }

    }

无论何时运行,它都会调用 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()


}

另外,我可以正常获取数据。

问题是它没有为表视图重新加载数据!!

有没有人知道为什么会这样?

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

 func gettingUserChatWithSUCCESS(responce: [chatRomModel]) {
        print("✅ getting chat room data SUCCESS")
        data = responce
        tableView.reloadData()
    }

【问题讨论】:

  • 当你从 API 收到数据时重新加载数据,实现 clsoure 以获取你的 api 数据到达的通知,然后你可以更新你的 tableview。
  • @ShauketSheikh 更新了问题,我忘记了将其添加到我的问题中的部分。我还添加了一个断点,但它不会重新加载表!
  • 在 DispatchQueue.main.async { } 中重新加载数据
  • 每次你创建不同的 ChatRoomViewController 对象时,如果你想在同一个视图控制器上重新加载它是行不通的,只需获取根视图控制器并重新加载它。
  • 您每次都以错误的方式使用它来创建 VC 吗?并检查您的 tableView numberOfRows 委托方法是否被调用?

标签: ios swift uitableview push-notification listener


【解决方案1】:

您可以使用通知观察器解决此问题,就像遵循此代码一样。

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

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

@objc func onReceiveData(_ notification:Notification) {
    // Do something now //reload tableview
}

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

NotificationCenter.default.post(name: Notification.Name("ReceiveData"), object: nil)

注意:- 当您的 viewcontrller 将消失时删除通知观察者,使用此代码

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

【讨论】:

  • 它正在导致某种崩溃!!!!在所有这些之后,它将应用程序中所有按钮的文本颜色更改为红色并禁用其中一些
  • 这非常有效。问题是,如果我在 viewWillDisappear 上删除观察者,它会在我将其称为我呈现的下一个屏幕之前将其删除。那我该如何删除呢?
  • 嗨 @Jalil 在 addObserver 之前删除观察者(首先删除现有的观察者并再次添加)。
  • 嗨@AtulParmar,如果我不删除它会发生什么?
【解决方案2】:

实现UNUserNotificationCenterDelegate 方法并发布您的通知。

func userNotificationCenter(_ center: UNUserNotificationCenter,
                            didReceive response: UNNotificationResponse,
                            withCompletionHandler completionHandler: @escaping () -> Void) {

    let userInfo = response.notification.request.content.userInfo
    if UIApplication.shared.applicationState == .background || UIApplication.shared.applicationState == .inactive {
                NotificationCenter.default.post(name: .newMessage, object: nil, userInfo:userInfo)
     }

}

在您的视图控制器中添加一个观察者来检查通知( 添加您自己的选择器方法。)

  NotificationCenter.default.addObserver(self,
                                        selector: #selector(updateMessages(notification:)),
                                        name: .newMessage,
                                        object: nil)



    @objc func updateMessages(notification: NSNotification) {
     // Handle your notifications...
   }

【讨论】:

    【解决方案3】:

    包括 SWIFT 5.4

    let myNotificationKey = "notificationKey" //Declare variable at the global level
    
    NotificationCenter.default.addObserver(self,
                                           selector: #selector(notifyMe),
                                           name: NSNotification.Name(rawValue: myNotificationKey),
                                           object: nil) //In First VC's viewDidLoad()
    
    func notifyMe() { print("Update tableview") } //In First VC
    
    NotificationCenter.default.post(name: Notification.Name(rawValue: myNotificationKey), object: self) 
    //Use this from you want to update the notification center for eg: OnClick of UIButton
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-21
      • 1970-01-01
      • 2019-07-04
      • 2011-10-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多