如果应用程序是通过本地通知启动的,则访问通知负载

Access Notification Payload if application is launched by local notification

如果用户在应用程序处于挂起状态时单击本地通知并启动应用程序,我如何才能收到通知并访问通知负载? 每当我的 iOS 应用程序从后台状态打开时,都会调用 UNNotification 响应函数。按键启动的本地通知已被弃用,我无法弄清楚如何确定应用程序是否已通过本地通知启动。我需要使用通知负载来正确填充视图控制器。

我正在使用此函数在应用程序处于后台状态时获取通知响应:

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

setup view here using payload
}

问题可能是您没有及早配置 UNUserNotificationCenterDelegate。您需要尽早执行此操作,如 didFinishLaunching,以便运行时知道将 didReceive 发送到何处。我是这样做的:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]?) -> Bool {
    let center = UNUserNotificationCenter.current()
    center.delegate = self.notifHelper
    return true
}