iOS 15系统如何发送仅播放声音不显示横幅的本地通知?
iOS 15 仅播放声音无横幅本地通知实现方案
iOS 15对本地通知的触发规则做了调整,无body/title字段的空通知会被系统直接过滤丢弃,因此原有实现失效。要实现仅播放声音、不展示通知横幅的效果,可按以下步骤修改:
步骤1:配置通知基础内容
给body字段赋值为空字符串满足系统触发要求,同时不要设置title、subtitle等展示类字段:
let center = UNUserNotificationCenter.current() let content = UNMutableNotificationContent() content.sound = UNNotificationSound(named: UNNotificationSoundName(rawValue: sound)) content.body = "" // 必填,设为空字符串即可 content.badge = nil // 不修改App角标
步骤2:注册自定义通知分类
在App启动阶段(如application:didFinishLaunchingWithOptions:方法中)注册专属通知分类,配置为默认隐藏预览:
let silentSoundCategory = UNNotificationCategory( identifier: "SilentSoundNotification", actions: [], intentIdentifiers: [], options: .hiddenPreviewsShowTitle ) UNUserNotificationCenter.current().setNotificationCategories([silentSoundCategory]) // 给上述通知内容关联该分类 content.categoryIdentifier = "SilentSoundNotification"
步骤3:实现通知展示代理控制
实现UNUserNotificationCenterDelegate的通知即将展示的代理方法,仅返回播放声音的配置:
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification) async -> UNNotificationPresentationOptions { guard notification.request.content.categoryIdentifier == "SilentSoundNotification" else { // 其他通知走原有展示逻辑 return [.alert, .sound, .badge] } // 仅保留声音播放选项,不展示横幅、角标 return .sound }
注意事项
- 需要提前向用户申请通知权限,确保声音播放权限已开启
- App在后台运行时该方案依然生效,无需额外开启后台刷新权限
- 不要给该类通知设置时间敏感等级,避免系统强制弹出通知横幅
内容的提问来源于stack exchange,提问作者iTarek
相关产品推荐
相关产品推荐

