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

Swift:getDeliveredNotifications最多仅返回100条通知的问题咨询

解决getDeliveredNotifications获取通知数量上限100的问题

问题原因

iOS系统的UNUserNotificationCenter提供的getDeliveredNotifications方法,默认仅会返回最近的100条已投递通知,这是系统层面的限制。因此当通知总数超过100后,通过notifications.count得到的数值会一直停留在100,无法反映真实的总通知数。

解决方案:本地维护通知计数

不要依赖系统返回的通知列表数量,改为自己在本地存储中维护通知计数,具体步骤如下:

  • 发送通知时更新计数
    每次发送通知前,先更新本地存储的计数,再设置通知的badge值:

    // 从UserDefaults获取当前计数,初始值为0
    var currentBadgeCount = UserDefaults.standard.integer(forKey: "AppNotificationBadgeCount")
    currentBadgeCount += 1
    UserDefaults.standard.set(currentBadgeCount, forKey: "AppNotificationBadgeCount")
    
    // 配置通知内容的badge
    let content = UNMutableNotificationContent()
    content.badge = NSNumber(value: currentBadgeCount)
    // 后续完成通知请求的创建与发送流程
    
  • 监听通知清除事件,同步计数
    实现UNUserNotificationCenterDelegate的方法,当用户清除通知时,同步减少本地计数:

    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        // 判断是否是用户清除通知的动作
        if response.actionIdentifier == UNNotificationDismissActionIdentifier {
            var currentCount = UserDefaults.standard.integer(forKey: "AppNotificationBadgeCount")
            currentCount = max(currentCount - 1, 0) // 确保计数不小于0
            UserDefaults.standard.set(currentCount, forKey: "AppNotificationBadgeCount")
            // 更新应用图标badge
            UIApplication.shared.applicationIconBadgeNumber = currentCount
        }
        completionHandler()
    }
    
  • 应用启动时同步系统与本地计数
    应用启动或进入前台时,同步系统当前的通知数与本地计数,避免出现不一致:

    UNUserNotificationCenter.current().getDeliveredNotifications { notifications in
        let systemNotificationCount = notifications.count
        let localCount = UserDefaults.standard.integer(forKey: "AppNotificationBadgeCount")
        // 取两者的最大值,确保本地计数反映真实状态
        let finalCount = max(systemNotificationCount, localCount)
        UserDefaults.standard.set(finalCount, forKey: "AppNotificationBadgeCount")
        UIApplication.shared.applicationIconBadgeNumber = finalCount
    }
    

替换原代码逻辑

原代码中直接使用notifications.count的逻辑需要替换为读取本地维护的计数,例如:

let currentCount = UserDefaults.standard.integer(forKey: "AppNotificationBadgeCount")
bestAttemptContent.badge = NSNumber(value: currentCount + 1)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 09:45:36