You need to enable JavaScript to run this app. iOS14应用后台/终止状态下处理FCM推送payload的实现咨询
优惠活动
大模型
产品
解决方案
定价
更多

iOS14应用后台/终止状态下处理FCM推送payload的实现咨询

核心结论

不需要改用外部存储,完全可以在当前App沙盒内的SQLite完成全部需求,仅需调整FCM payload结构和iOS端回调逻辑即可解决后台/终止状态下的payload处理问题。

问题根因

当前回调不触发本质是iOS推送的系统规则限制:

  • 若FCM payload携带notification顶级字段,属于展示型通知:App在后台/被终止时,APNs会直接渲染通知,不会唤醒App执行任何代码,仅当用户手动点击通知时才会唤起App
  • didReceiveRemoteNotification(_:fetchCompletionHandler:)回调仅在以下条件全部满足时触发:
    • FCM payload携带content_available: 1后台唤醒标记
    • App未被用户从多任务界面手动划掉杀死
    • 系统出于省电策略调度唤醒,不保证实时触发
  • 现有代码遗漏了该回调的completionHandler调用,系统会在数据处理完成前就挂起App,导致SQLite写入中断

分步实现方案

1. 调整FCM下发的Payload结构

根据业务需求选择两种payload配置:

  • 需要后台静默处理+用户可见通知:同时携带notification、data字段和后台唤醒标记,示例结构:
{
  "to": "目标FCM Token",
  "content_available": true,
  "priority": "high",
  "notification": {
    "title": "新联系人提醒",
    "body": "有新的联系人需要处理"
  },
  "data": {
    "name": "测试联系人",
    "phone": "13800138000",
    "isLocalized": "1",
    "longitude": "116.397128",
    "latitude": "39.916527"
  }
}
  • 纯静默后台处理:仅保留data字段和后台唤醒标记,不添加notification字段,需自行触发本地通知展示

2. 补全iOS端回调逻辑

2.1 修复后台唤醒回调实现

必须在SQLite写入完成后调用系统提供的completionHandler,避免任务被提前终止:

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
    // 提取公共处理逻辑
    let isSuccess = handleNotificationPayload(userInfo)
    // 按处理结果回调系统
    completionHandler(isSuccess ? .newData : .noData)
}

2.2 提取公共payload处理方法

复用代码处理不同场景下的payload,同时申请额外后台执行时间避免任务超时:

private var backgroundTaskID: UIBackgroundTaskIdentifier = .invalid
@discardableResult
private func handleNotificationPayload(_ userInfo: [AnyHashable: Any]) -> Bool {
    // 校验payload字段合法性
    guard let name = userInfo["name"] as? String,
          let phone = userInfo["phone"] as? String,
          let isLocalizedStr = userInfo["isLocalized"] as? String,
          let longitudeStr = userInfo["longitude"] as? String,
          let latitudeStr = userInfo["latitude"] as? String else {
        return false
    }

    // 申请后台任务时间,避免系统提前挂起App
    backgroundTaskID = UIApplication.shared.beginBackgroundTask(withName: "FCMPayloadHandler") {
        // 超时自动清理任务
        UIApplication.shared.endBackgroundTask(self.backgroundTaskID)
        self.backgroundTaskID = .invalid
    }

    // 执行SQLite写入操作
    ContactsService.sharedInstance.addAlert(
        phoneNumber: phone,
        name: name,
        isLocalized: Bool(isLocalizedStr) ?? false,
        longitude: Double(longitudeStr) ?? 0,
        latitude: Double(latitudeStr) ?? 0
    )

    // 处理完成后结束后台任务
    UIApplication.shared.endBackgroundTask(backgroundTaskID)
    backgroundTaskID = .invalid
    return true
}

2.3 覆盖用户点击通知/冷启动场景

当App被手动杀死后,需通过通知点击回调、冷启动参数补处理payload:

  1. 实现UNUserNotificationCenterDelegate捕获通知点击事件:
extension AppDelegate: UNUserNotificationCenterDelegate {
    // 用户点击通知时触发
    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        handleNotificationPayload(response.notification.request.content.userInfo)
        completionHandler()
    }

    // 前台收到通知的展示逻辑,可按需配置
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        completionHandler([.alert, .sound, .badge])
    }
}
  1. 在App启动方法中读取推送冷启动的payload:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    FirebaseApp.configure()
    UNUserNotificationCenter.current().delegate = self
    let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
    UNUserNotificationCenter.current().requestAuthorization(options: authOptions) { _, _ in }
    application.registerForRemoteNotifications()
    Messaging.messaging().delegate = self

    // 处理通过推送冷启动的payload
    if let remoteNotification = launchOptions?[.remoteNotification] as? [AnyHashable: Any] {
        handleNotificationPayload(remoteNotification)
    }
    return true
}

注意事项

  • 系统后台任务的最长执行时间为30秒,SQLite写入操作需控制在该时限内完成,不要附加额外耗时网络请求
  • 若App被用户从多任务界面手动划掉杀死,iOS系统默认不会自动唤醒App处理推送,需等用户下次打开App时通过上述启动/通知点击逻辑补处理数据,该限制无法绕过
  • 所有操作均在App沙盒内完成,无需使用任何外部存储方案

内容的提问来源于stack exchange,提问作者Jorge Morata Toribio

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.21 07:45:02