求助:iOS12+Swift4环境下无法清除通知中心本地/远程通知
解决iOS 12下清除通知中心通知的问题
你遇到的问题挺典型的——iOS 12开始,苹果把本地和远程通知的管理逻辑从UIApplication迁移到了UserNotifications框架,原来的cancelAllLocalNotifications()和直接设置applicationIconBadgeNumber的方式已经没法完全生效了。下面给你适配iOS 12的具体解决方案:
1. 先导入必要的框架
确保你的代码顶部导入了UserNotifications:
import UserNotifications
2. 清除所有通知(本地+远程)
用UNUserNotificationCenter的实例来处理通知清除,同时同步更新应用图标角标:
// 清除所有待发送的本地通知请求 UNUserNotificationCenter.current().removeAllPendingNotificationRequests() // 清除通知中心里已经展示的所有通知 UNUserNotificationCenter.current().removeAllDeliveredNotifications() // 更新应用图标角标(兼容旧版本写法) UIApplication.shared.applicationIconBadgeNumber = 0 // iOS 10+ 更推荐的角标更新方式,带错误回调 UNUserNotificationCenter.current().setBadgeCount(0) { error in if let error = error { print("更新角标失败:\(error.localizedDescription)") } }
3. 针对远程通知的额外提示
如果你的远程通知是通过APNs推送的,除了上面的代码,还要注意:
- 后续推送时,如果需要彻底清除角标,服务器端的推送payload里要把
badge字段设为0,不然新推送可能又会让角标回来 - 如果你只想清除特定几条通知,可以用
removeDeliveredNotifications(withIdentifiers:)方法,传入对应通知的ID数组就行
4. 测试验证小技巧
测试的时候可以按这个流程来:
- 先手动触发几条本地通知,或者让服务器推送几条远程通知到通知中心
- 调用上面的代码后,回到主屏幕下拉通知中心,确认通知是否被清空
- 检查应用图标上的角标是否已经变成0
要注意,iOS 12及以上版本里,UIApplication的cancelAllLocalNotifications()已经被标记为废弃,必须用UserNotifications框架的API才能正常清除通知中心的内容。
内容的提问来源于stack exchange,提问作者bablu s nair
相关产品推荐
相关产品推荐

