首页 > 解决方案 > SwiftUI 通知单击转到特定视图

问题描述

我正在使用 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

        }
    

    }

}

标签: iospush-notificationswiftuiios14firebase-notifications

解决方案


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

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

在 中AppDelegate,我将此属性设置trueuserNotificationCenter( ... willPresent ...)(应用程序处于活动状态时的通知)或userNotificationCenter( ... didReceive ...)(应用程序处于后台时的通知)函数内部。

既然AppDelegate是一个ObservableObject,它可以被设置为一个environmentObjectContentView :

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

    }

}

我将 EnvironmentObject 传递delegate给 SpecialView(),以便在openedFromNotification需要再次显示标准 HomeView() 时将属性设置回 false。

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

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


推荐阅读