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

10

我正在使用SwiftUI。

我希望在点击推送通知时打开除根视图之外的特定屏幕。有几种使用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()
    }
    ... }

你找到答案了吗? - Adit Gupta
这个问题并没有太多意义,因为userNotificationCenter(_ center: UNUserNotificationCenter, didReceive...)在应用程序处于后台时被调用,所以此时没有UI存在,你只需要将通知响应数据存储在某个地方,以便稍后向用户显示,当用户打开应用程序时,应用程序就像正常流程一样运行(例如从数据库中读取记录、默认值等)。 - Asperi
这里有一个与你类似的问题,也许答案会有所帮助:https://stackoverflow.com/questions/60490860/display-a-view-after-receiving-apns-with-swiftui - Jonas Deichelmann
1个回答

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")
            }
        }
    }
    
}

我希望这个样例能够帮助你。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接