SwiftUI willFinishLaunchingWithOptions 有 launchOptions = nil

SwiftUI willFinishLaunchingWithOptions has launchOptions = nil

我已经为 Firebase 通知注册了该应用程序,并且我已经实施了 UNUserNotificationCenterDelegate。当应用程序处于 运行 或在后台时,将调用 didReceive 方法。

当我终止应用程序并发送通知时。 willFinishLaunchingWithOptionsdidFinishLaunchingWithOptions 方法被调用,但 launchOptions 对象为 nil 且不包含任何 .remoteNotificaiton 键。

if launchOptions != nil {
            logger.log("There is stuff in launch options")
        }

我的 AppDelegate 设置


@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate 

@available(iOS 10, *)
extension AppDelegate: UNUserNotificationCenterDelegate 

extension AppDelegate: MessagingDelegate

以上代码从不向控制台打印任何日志消息。

我什么都试过了 google 但没有什么具体的。

我正在使用 iOS 14 beta 6 和 Xcode beta 6。

提前致谢。

您可以通过 connectionOptions.notificationResponse

从 SceneDelegate 而不是 AppDelegate 获得通知

来自 https://dev.to/nemecek_f/ios-13-launchoptions-always-nil-this-is-the-reason-solution-kki &

func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
   if let notificationResponse = connectionOptions.notificationResponse {
          // you can get notification here
        }        

        let contentView = ContentView()

        if let windowScene = scene as? UIWindowScene {
            let window = UIWindow(windowScene: windowScene)
            window.rootViewController = UIHostingController(rootView: contentView)
            self.window = window
            window.makeKeyAndVisible()
        }
    }

[更新] 即使应用程序未启动,您也可以从 userNotificationCenter 收到通知

func userNotificationCenter(_ center: UNUserNotificationCenter,
                                didReceive response: UNNotificationResponse,
                                withCompletionHandler completionHandler: @escaping () -> Void) {
        print("open notification")
        let userInfo = response.notification.request.content.userInfo
        
        print(userInfo)
        completionHandler()
    }