如何在 IOS 应用收到 FCM 通知时更新 table 视图

How to update table view when IOS app receives FCM notification

我是 Swift 和 Firebase 的新手,我在更新 table 时遇到了问题。我的应用程序在主页上有一个 table 视图。我希望应用程序会在每次收到前台和后台 FCM 通知时更新 table。

在前台,如何更新table视图,当应用程序在前台收到FCM通知时,我应该执行什么功能或操作来刷新或更新table视图?

在后台,我如何同时更新 table 视图?一般情况下,应用程序会自动刷新页面还是我应该自己更新?

有人可以帮我解决这个问题吗?谢谢!

您可以期望推送通知以您的 AppDelegate 的方法传送。之后你可以 post 一个 NSNotificationCenter 广播。

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
                 fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
  NotificationCenter.default.post(name: "AppNotification", object: "myObject", userInfo: userInfo)
}

您的视图控制器可以观察和刷新您的 table 视图。

在你的ViewController中:

func viewDidLoad() {
    NotificationCenter.default.addObserver(self, selector: #selector(appnotification), name: "AppNotification", object: nil)
}

@objc func appnotification(notification: Notification) {
    print(notification.userInfo ?? "")
    yourTableView.reloadData()
}