【问题标题】:I want to tap a push notification to open a specific screen in SwiftUI我想点击推送通知以在 SwiftUI 中打开特定屏幕
【发布时间】:2020-07-27 23:24:53
【问题描述】:

我正在使用 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()
    }
    ... }

【问题讨论】:

  • 你找到答案了吗?
  • 这个问题没有多大意义,因为userNotificationCenter(_ center: UNUserNotificationCenter, didReceive... 是在应用程序处于后台时调用的,因此此时不存在 UI,您只需将通知响应数据存储在某处以便稍后向用户显示,当用户打开一个应用程序,但随后应用程序的行为与常规流程一样(例如,从数据库、默认值等读取记录)
  • 这里有一个和你类似的问题,也许答案会有所帮助:stackoverflow.com/questions/60490860/…

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


【解决方案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")
            }
        }
    }
    
}

我希望这个示例可以帮助到你。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-07-02
    • 1970-01-01
    • 2017-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多