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

时间:2020-04-15 04:06:37

标签: swift push-notification swiftui apple-push-notifications

我正在使用SwiftUI。

我想通过单击推送通知来打开除“根视图”之外的特定屏幕。有多种使用StoryBoard打开它的方法,但并非没有StoryBoard。

不使用StoryBoard如何实现?

我尝试过this,但是我是初学者,所以我不知道。

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()
    }
    ... }

1 个答案:

答案 0 :(得分: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
        // ...
    
}

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

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

我希望这个示例可以为您提供帮助。