You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

App处于杀死/终止状态时,点击通知didReceive函数未触发

问题分析与解决方案

当App处于杀死/终止状态时,点击通知后UNUserNotificationCenter的didReceiveResponse方法未被触发,但前台、后台状态下功能正常,核心原因是通知响应事件的触发时机早于UNUserNotificationCenterDelegate的绑定完成时间。

你的代码中initNotification方法把设置代理的逻辑放到了DispatchQueue.global().async异步队列中,而App从杀死状态通过点击通知启动时,系统会优先处理通知响应事件,此时异步队列的代理绑定代码还未执行,自然无法触发回调方法。

具体修复步骤:

  1. 移除异步队列,同步设置代理
    去掉异步执行逻辑,直接在主线程同步完成UNUserNotificationCenter的代理绑定,确保App启动时立刻完成代理关联:
class MCNotificationDelegate: FlutterAppDelegate {

   /// 从AppDelegate的didFinishLaunchingWithOptions中初始化通知配置
   public func initNotification() {
        // 移除异步队列,直接在主线程设置代理
        UNUserNotificationCenter.current().delegate = self
        UIApplication.shared.registerForRemoteNotifications()
    }

    // 其余原有方法保持不变
}
  1. 在didFinishLaunchingWithOptions中处理启动时的通知信息
    当App从杀死状态被通知唤醒时,通知的userInfo会包含在launchOptions的.remoteNotification键中,需要在这里额外处理一次,避免因代理绑定时机问题导致的逻辑遗漏:
@objc class AppDelegate: MCNotificationDelegate {
    override func application(
        _ application: UIApplication,
        didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
    ) -> Bool {
       // 优先初始化通知代理
       self.initNotification()
       
       // 处理启动时携带的通知信息
       if let remoteNotification = launchOptions?[.remoteNotification] as? [String: Any] {
           // 这里复用didReceiveResponse中的处理逻辑
           DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
               UserDefaults.standard.set("\(remoteNotification)", forKey: "sfmc_didReceive")
           }
       }
       ....
       return true
    }
}

验证建议:

  • 杀死App后发送远程通知,点击通知启动App
  • 直接在处理逻辑中添加日志打印(去掉asyncAfter延迟),快速验证是否触发了处理逻辑

内容的提问来源于stack exchange,提问作者Bhagat Singh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 01:43:34