ios - 处理用户点击通知时的去向?
问题描述
我有几种不同类型的通知,当单击通知时,所有这些都应将用户带到不同的视图控制器。
应该如何处理(顺便说一下,我使用的是 Swift 5)?从我的研究中,我看到人们倾向于在AppDelegate
'sdidReceive
函数中呈现一个新的视图控制器,但是为几个不同的视图控制器做所有的逻辑,AppDelegate
似乎都是错误的。这真的是正确的做法吗?
此外,我使用 Firebase 从后端向设备发送消息。我有一个单独的类,FirebaseUtils
我在其中处理传递的数据的所有逻辑。从这里展示视图控制器会更好吗?如果是这样,如果没有根视图控制器,我将如何做到这一点?
解决方案
我通常按照这些思路设置一些东西(未经测试):
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 内部四处乱窜,这也是正确的。
推荐阅读
- python - Tensorflow Object Detection API Untrained Faster-RCNN 模型
- redux - 在 Jest 测试中找不到 redux 连接中的商店
- wordpress - 如何在 Wordpress 中编写个性化端点?
- angular - switchMap 和 debounceTime 取消挂起
- dns - spf 记录参数“all”等于“+all”?
- excel - 在其他地方输入相同数据时删除旧条目?
- javascript - 打开菜单时如何将滚动位置始终固定在容器顶部?
- python - 为什么 Python 无法检索环境变量的值,即使该变量在通过 bash 测试时具有值?
- c# - UWP BarcodeScanner 预览:CaptureElement 不显示任何预览
- laravel - 如何获取 laravel nova 服务器错误消息并自定义它