我通常按照以下方式进行设置(未经测试):
- 为可能处理通知的事物创建
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