SwiftUI 通知单击转到特定视图

2024-01-03

我正在使用 SwiftUI 2.0,我正在尝试实现 firebase 推送通知。 在新的 SwiftUI 应用程序结构中,没有 AppDelegate 和 SceneDelegate,因此我创建了 AppDelegate 类。我设法接收通知,但无法在单击通知时转到特定视图。 这是我的代码:

@main
struct swiftUiApp: App {


@UIApplicationDelegateAdaptor(AppDelegate.self) var delegate


var body: some Scene {
    WindowGroup {
       
            ContentView() 
         
    }
  } 
}

和 AppDelegate 扩展:

func userNotificationCenter(_ center: UNUserNotificationCenter,
                          didReceive response: UNNotificationResponse,
                          withCompletionHandler completionHandler: @escaping () -> Void) {

let  orders =  Orders()

let userInfo = response.notification.request.content.userInfo
// Print message ID.
if let messageID = userInfo[gcmMessageIDKey] {
  print("Message ID: \(messageID)")
}

if(userInfo["gcm.notification.type"] != nil){
    if(userInfo["gcm.notification.type"] as! String == "order"){
  
          //here I need to navigate to OrderView

        }
    

    }

}

我面临着完全相同的问题并以这种方式解决:

我有我的AppDelegate类符合ObservableObject并添加了一个已发布的属性来控制是否需要显示特定于通知的视图:@Published var openedFromNotification: Bool = false

In the AppDelegate,我将此属性设置为true在 - 的里面userNotificationCenter( ... willPresent ...)(应用程序处于活动状态时通知)或userNotificationCenter( ... didReceive ...)(应用程序在后台时的通知)功能。

Since AppDelegate is an ObservableObject,它可以被设置为environmentObject对于内容视图:

@main
struct swiftUiApp: App {

@UIApplicationDelegateAdaptor(AppDelegate.self) var delegate

var body: some Scene {
     
     WindowGroup {
        
        ContentView().environmentObject(delegate)
     
     }
  } 
}

这使我可以访问 ContentView() 内已发布的属性。

在 ContentView 内部,我只是根据应用程序正常打开时显示特定于通知的视图或标准视图delegate.openedFromNotification财产:

struct ContentView: View {
    
    @EnvironmentObject private var delegate: AppDelegate
    
    var body: some View {

       if (delegate.openedFromNotification) {
          SpecialView().environmentObject(delegate)
       } else {
           HomeView()
       }

    }

}

我传递了环境对象delegate到 SpecialView() 以便我可以设置openedFromNotification一旦我需要再次显示标准 HomeView() ,属性就会返回 false。

如果您希望显示不同的视图,例如,可以通过添加更多已发布的属性来扩展此功能。某些通知负载。

就我而言,我有两个这样的已发布属性,并且根据推送通知数据中的 JSON 值,我可以将用户导航到应用程序的不同部分。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

SwiftUI 通知单击转到特定视图 的相关文章

随机推荐