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

iOS17中UIApplication.applicationIconBadgeNumber弃用,如何改用setBadgeCount方法?

解决iOS 17+中applicationIconBadgeNumber弃用问题

在iOS 17及以上版本,UIApplication.shared.applicationIconBadgeNumber已被弃用,官方推荐使用UNUserNotificationCenter的setBadgeCount(_:withCompletionHandler:)方法替代。修改步骤如下:

  1. 导入UserNotifications框架
    在你的Swift文件顶部添加导入语句:

    import UserNotifications
    
  2. 替换.onAppear中的代码
    将原有代码替换为调用UNUserNotificationCenter的方法:

    .onAppear {
        UNUserNotificationCenter.current().setBadgeCount(0) { error in
            // 可选:处理设置失败的情况
            if let error = error {
                print("清除应用角标失败:\(error.localizedDescription)")
            }
        }
    }
    
  3. 注意权限问题
    如果你的App尚未请求过通知权限,需先获取.badge权限才能正常设置角标。可在App启动时或首次需要设置角标前添加权限请求:

    UNUserNotificationCenter.current().requestAuthorization(options: [.badge]) { granted, error in
        if let error = error {
            print("请求通知权限失败:\(error.localizedDescription)")
        }
        // 权限获取成功后再执行角标设置操作
        if granted {
            UNUserNotificationCenter.current().setBadgeCount(0) { _ in }
        }
    }
    

内容的提问来源于stack exchange,提问作者Tobias Carlo Oettli

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 16:22:04