ios - SwiftUI 通知单击转到特定视图
问题描述
我正在使用 SwiftUI 2.0,并且正在尝试实现 firebase 推送通知。在新的 SwiftUI 应用结构中,没有 AppDelegate 和 SceneDelegate,所以我创建了 AppDelegate 类。我设法接收通知,但我无法在通知点击时转到特定视图。这是我的代码:
@main
struct swiftUiApp: App {
@UIApplicationDelegateAdaptor(AppDelegate.self) var delegate
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
和 AppDelegate 扩展:
func userNotificationCenter(_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: @escaping () -> Void) {
let orders = Orders()
let userInfo = response.notification.request.content.userInfo
// Print message ID.
if let messageID = userInfo[gcmMessageIDKey] {
print("Message ID: \(messageID)")
}
if(userInfo["gcm.notification.type"] != nil){
if(userInfo["gcm.notification.type"] as! String == "order"){
//here I need to navigate to OrderView
}
}
}
解决方案
我面临着完全相同的问题并以这种方式解决了它:
我让我的AppDelegate
类符合ObservableObject
并添加了一个已发布的属性,该属性控制我是否需要显示特定于通知的视图:@Published var openedFromNotification: Bool = false
在 中AppDelegate
,我将此属性设置true
为userNotificationCenter( ... willPresent ...)
(应用程序处于活动状态时的通知)或userNotificationCenter( ... didReceive ...)
(应用程序处于后台时的通知)函数内部。
既然AppDelegate
是一个ObservableObject
,它可以被设置为一个environmentObject
ContentView :
@main
struct swiftUiApp: App {
@UIApplicationDelegateAdaptor(AppDelegate.self) var delegate
var body: some Scene {
WindowGroup {
ContentView().environmentObject(delegate)
}
}
}
这使我可以访问我的 ContentView() 中的已发布属性。
在 ContentView 中,我只是根据delegate.openedFromNotification
属性显示应用程序正常打开时的特定通知视图或标准视图:
struct ContentView: View {
@EnvironmentObject private var delegate: AppDelegate
var body: some View {
if (delegate.openedFromNotification) {
SpecialView().environmentObject(delegate)
} else {
HomeView()
}
}
}
我将 EnvironmentObject 传递delegate
给 SpecialView(),以便在openedFromNotification
需要再次显示标准 HomeView() 时将属性设置回 false。
如果您希望为某些通知有效负载显示不同的视图,可以通过添加更多已发布的属性来扩展此功能。
就我而言,我有两个这样的已发布属性,并且基于推送通知数据中的 JSON 值,我可以将用户导航到我的应用程序的不同部分。
推荐阅读
- python - 无法索引 numba 类型
- rust - 为什么移动字符串变量会在这里出错?
- android - Android Webview 警报对话框按钮 白色
- c# - 抛出异常:尝试简单插入 SQL Server 数据库时 System.Data.dll 中的“System.Data.SqlClient.SqlException”
- javascript - jQuery Datatables 排序和搜索的间歇性问题
- css - 在列中居中输入组
- list - 无法在 ValueListenableBuilder 中返回更新的小部件
- flutter - 在对象方法中颤振空安全条件
- verilog - always_latch 的复位信号的复位类型是什么?
- c++ - 类方法中的 Cout 什么都不做