单击通知时如何处理用户去向?

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

应该如何处理(顺便说一句,我正在使用Swift 5)?从我的研究中,我发现人们倾向于在AppDelegate的{​​{1}}函数中展示一个新的视图控制器,但是对所有不同的视图控制器,所有逻辑都在{{1} }似乎是错误的。这真的是正确的方法吗?

此外,我正在使用Firebase从后端向设备发送消息。我有一个单独的类didReceive,在其中处理传递的数据的所有逻辑。从这里介绍视图控制器会更好吗?如果是这样,没有根视图控制器怎么办?

hinaliuyinyuan1 回答:单击通知时如何处理用户去向?

我通常按照以下方式进行设置(未经测试):

  • 为可能处理通知的事物创建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内部探查,这也是正确的。

,

这样对您有用吗?

struct NotificationPresenter {
   func present(notification: [AnyHashable: Any],from viewController: UIViewController) {
      let notificationViewController: UIViewController

      // decide what type of view controller to show and set it up

      viewController.present(notificationViewController,animated: true,completion: nil)
   }
}
extension UIViewController {
   static func topViewController(_ parentViewController: UIViewController? = nil) -> UIViewController {
      guard let parentViewController = parentViewController else {
         return topController(UIApplication.shared.keyWindow!.rootViewController!)
      }

      return parentViewController.presentedViewController ?? parentViewController
   }
}

let notificationPresenter = NotificationPresenter()

func application(_ application: UIApplication,didReceiveRemoteNotification userInfo: [AnyHashable: Any],fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
   notificationPresenter.present(userInfo,from: UIViewController.topViewController())
}


本文链接:https://www.f2er.com/3156181.html

大家都在问