我想点击推送通知以在 SwiftUI 中打开特定屏幕

Ika*_*Ika 9 push-notification apple-push-notifications swift swiftui

我正在使用 SwiftUI。

我想通过单击推送通知来打开 Root View 以外的特定屏幕。有几种方法可以使用 StoryBoard 打开它,但不能没有 StoryBoard。

如何在不使用 StoryBoard 的情况下实现它?

我试过这个,但我是初学者,所以我不知道。

class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {
    var window: UIWindow?

    func userNotificationCenter(
        _ center: UNUserNotificationCenter,
        willPresent notification: UNNotification,
        withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions)
        -> Void) {
        completionHandler([.alert, .badge, .sound])
    }

    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: () -> Void) {
        // I want to open a screen other than Root View here.
        completionHandler()
    }
    ... }
Run Code Online (Sandbox Code Playgroud)

Moh*_*ani 1

这个想法是,当用户收到通知时设置一个变量,并在想要显示 UI 时检查该变量。

这是一个示例:

// assume that AppDelegate is also our UNNotificationCenterDelegate 
// I'm using a bool variable to check if user is coming from the notification
var isFromNotif: Bool = false
extension AppDelegate: UNUserNotificationCenterDelegate {
    
    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        
        isFromNotif = true
        // ...
    
}
Run Code Online (Sandbox Code Playgroud)

现在在我的中View,我检查标志。

struct ContentView1: View {
    
    var body: some View {
        return Group {
            if isFromNotif {
                Text("coming from notification")
            } else {
                Text("not coming from notification")
            }
        }
    }
    
}
Run Code Online (Sandbox Code Playgroud)

我希望这个样本可以帮助你。