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

iOS 16.6.1中didReceiveRemoteNotification后台不触发问题求助

Firebase后台推送未触发didReceiveRemoteNotification导致角标无法更新

开发一款简易聊天应用,需求是收到Firebase推送通知时更新应用角标数字。当前遇到的问题:

  • 应用处于前台时,didReceiveRemoteNotification方法正常调用,角标更新正常;
  • 应用处于后台时,设备能收到通知且userInfo数据正确,但didReceiveRemoteNotification方法未被触发,无法更新角标;
  • Firebase控制台可正常推送通知。

相关代码

推送接收方法

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

角标更新逻辑

private func updateNotificationBadge(application: UIApplication, userInfo: [AnyHashable : Any]){
    let notificationType = userInfo["notificationType"] as? String
    print("\(notificationType) APN recieved: \(userInfo)")
    print(userInfo)

    let state = application.applicationState

    let userDefaults = UserDefaults.standard
    var badgeCount = userDefaults.integer(forKey: "badgeCount")
    if badgeCount > 0 {
        badgeCount += 1
    } else {
        badgeCount = 1
    }
    userDefaults.set(badgeCount, forKey: "badgeCount")
}

已尝试的无效操作

  1. 调整推送通知发送逻辑
func sendPushNotification(token: String, title: String, body: String, notificationType: ATCNotificationType, payload: [String: String]) {
    var data = payload
    data["notificationType"] = notificationType.rawValue
    let paramString: [String : Any] = [
        "to" : token,
        "content-available": 1,
        "priority":"high",
        "notification" : ["title" : title, "body" : body, "sound": "default"],
        "aps":["content-available":1,
               "apns-priority":5,
               "apns-push-type":"background",
               "badge":0],
        "data" : data
    ]
    handlePushNotification(with: paramString)
}
  1. 已开启XCode Capabilities中推送通知、后台模式(远程通知)相关权限

  2. 尝试两种推送接收方法重载

private func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
    self.updateNotificationBadge(application: application, userInfo: userInfo)
}

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
    self.updateNotificationBadge(application: application, userInfo: userInfo)
}
  1. 确认应用未处于终止状态(仅后台运行)

内容的提问来源于stack exchange,提问作者Jeff Yeung Sam Wai

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 04:12:46