AppDelegate 方法仅在应用程序已打开时从通知中调用

Posted

技术标签:

【中文标题】AppDelegate 方法仅在应用程序已打开时从通知中调用【英文标题】:AppDelegate method is only called from a notification when the app is already open 【发布时间】:2020-10-09 19:26:25 【问题描述】:

我正在尝试让推送通知在按下时将用户带到特定的视图控制器。

我目前在我的AppDelegate 中有这个:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool 
    UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge])  granted, error in
        if let error = error 
            print(error.localizedDescription)
         else 
            application.registerForRemoteNotifications()
        
    
    
    UNUserNotificationCenter.current().delegate = self

    return true

当我按下通知并从后台打开应用程序时,这些都不会被调用:

func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) 
    
    completionHandler([.alert, .sound, .badge])


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



func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) 


【问题讨论】:

【参考方案1】:

如果您的应用没有在后台运行,您将像这样处理didFinishLaunchingWithOptions 中的通知

let notificationInfo = launchOptions?[UIApplication.LaunchOptionsKey.remoteNotification] as? [String : Any]

如果您的应用在后台/前台运行,您将处理通知点击

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

【讨论】:

以上是关于AppDelegate 方法仅在应用程序已打开时从通知中调用的主要内容,如果未能解决你的问题,请参考以下文章

UI 元素仅在焦点从原始按钮/输入移开时更新

AppDelegate 代码仅在后台运行

appdelegate 中的 NSURLSessionDataTask

HKObserverQuery 仅在应用程序重新打开时运行

仅在模态打开时加载 iframe src

仅在一个 ViewController 中更改导航栏属性