首页 > 解决方案 > 处理用户点击通知时的去向?

问题描述

我有几种不同类型的通知,当单击通知时,所有这些都应将用户带到不同的视图控制器。

应该如何处理(顺便说一下,我使用的是 Swift 5)?从我的研究中,我看到人们倾向于在AppDelegate'sdidReceive函数中呈现一个新的视图控制器,但是为几个不同的视图控制器做所有的逻辑,AppDelegate似乎都是错误的。这真的是正确的做法吗?

此外,我使用 Firebase 从后端向设备发送消息。我有一个单独的类,FirebaseUtils我在其中处理传递的数据的所有逻辑。从这里展示视图控制器会更好吗?如果是这样,如果没有根视图控制器,我将如何做到这一点?

标签: iosswiftapple-push-notificationsswift5

解决方案


我通常按​​照这些思路设置一些东西(未经测试):

  • NotificationHandler为可能处理通知的事物创建协议
protocol NotificationHandler {
    static func canHandle(notification: [AnyHashable : Any])
    static func handle(notification: [AnyHashable : Any], completionHandler: @escaping (UIBackgroundFetchResult) -> Void)
}
  • 在 AppDelegate 中创建一个notificationHandlers变量,并用可能想要处理通知的内容填充它。
let notificationHandlers = [SomeHandler.self, OtherHandler.self]

didReceive中,遍历处理程序,询问每个处理程序是否可以处理通知,如果可以,则告诉它这样做。

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {

    guard let handler = notificationHandlers.first(where: 
        { $0.canHandle(notification: userInfo) }) {
    else {
        return
    }

    handler.handle(notification: userInfo, completionHandler: completionHandler)
}

这种方法将逻辑保持在 AppDelegate 之外,这是正确的,并且可以防止其他类型在 AppDelegate 内部四处乱窜,这也是正确的。


推荐阅读