Swift本地通知在勿扰模式下的送达问题及解决方案问询
勿扰模式下本地通知无法送达的解决办法
一、用「关键提醒」突破勿扰模式
这就是你要找的类似“紧急通知”的机制,能直接绕过勿扰和静音状态,强制推送通知并播放声音,但有几个前提条件:
- 必须在
Info.plist中添加NSCriticalAlertUsageDescription键,明确说明使用关键提醒的理由(苹果审核必填) - 仅支持iOS 12及以上版本
- 自定义声音需为PCM或IMA4编码,时长不超过30秒
修改你的代码如下:
let content = UNMutableNotificationContent() content.title = String(localized: "proTimer") content.body = String(localized: "\(name)IstAbgelaufen") // 设置关键提醒声音,音量设为1.0(最大) content.sound = UNNotificationSound.criticalSoundNamed(UNNotificationSoundName("\(sound).wav"), withAudioVolume: 1.0) // 标记为关键级中断,确保最高优先级 content.interruptionLevel = .critical let trigger = UNTimeIntervalNotificationTrigger(timeInterval: endDate!.timeIntervalSince(Date.now), repeats: false) let request = UNNotificationRequest(identifier: id.uuidString, content: content, trigger: trigger) UNUserNotificationCenter.current().add(request)
二、申请关键提醒权限
普通通知权限不包含关键提醒权限,需要单独申请:
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .criticalAlert]) { granted, error in if let error = error { print("权限请求失败:\(error.localizedDescription)") } }
三、折中方案:时间敏感型通知
如果不想使用权限要求严格的关键提醒,可将通知设置为「时间敏感型」,它能在勿扰模式下正常显示,但不会强制播放声音(具体表现取决于用户设置):
content.interruptionLevel = .timeSensitive
对应的权限请求需要加上.timeSensitive选项:
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .timeSensitive]) { granted, error in // 处理权限结果 }
内容的提问来源于stack exchange,提问作者IOSCodingMax
相关产品推荐
相关产品推荐

