用户打开通知时,如何在SwiftUI中打开特定的视图?

时间:2020-06-10 17:09:47

标签: ios swiftui

首先,我如何检查用户是否打开了通知? (在所有情况下,当手机被锁定,应用程序处于前台状态以及应用程序处于后台状态时)

如果电话已锁定,或者尚未启动应用程序,是否像在AppDelegate的application()中检查启动选项一样简单?例如:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    let notificationOption = launchOptions?[.remoteNotification]
}

对于其他两种情况(前景和背景),在这些情况下可以检查哪些功能?他们还会继续使用AppDelegate吗?

第二,当我设置功能来检查是否已从通知中打开应用程序时,如何将SwiftUI导航到特定视图?在这种情况下,它将只是一个特定的TabView标签。

我目前在SceneDelegate中初始化我的tabViewModel,并在那里设置默认的当前标签。例如,currentTab = 2。

TabView(selection: $tabViewModel.currentTab) {
   ...
}

1 个答案:

答案 0 :(得分:0)

当应用为前景或背景时,将调用userNotificationCenterUNUserNotificationCenterDelegate。当应用未启动时,您可以使用SceneDelegate scene connectionOptions查看通知。

func userNotificationCenter(_ center: UNUserNotificationCenter,
                                didReceive response: UNNotificationResponse,
                                withCompletionHandler completionHandler: @escaping () -> Void) {
        print("open notification")
        let userInfo = response.notification.request.content.userInfo
        
        print(userInfo)
        completionHandler()
    }
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
   if let notificationResponse = connectionOptions.notificationResponse {
          // you can get notification here
        }        

        let contentView = ContentView()

        if let windowScene = scene as? UIWindowScene {
            let window = UIWindow(windowScene: windowScene)
            window.rootViewController = UIHostingController(rootView: contentView)
            self.window = window
            window.makeKeyAndVisible()
        }
    }

[UPDATE] 即使应用未启动,您也不需要SceneDelegate scene connectionOptions.userNotificationCenter支持在应用程序为前台,背景且未启动应用程序时使用。 https://stackoverflow.com/a/60857140/12208004