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

如何在Swift中创建关键本地通知?代码实现遇阻求助

关键本地通知不生效的排查与修复步骤

1. 配置关键通知权限

首先必须在Info.plist中添加权限描述,否则无法请求关键通知权限:

<key>NSCriticalAlertUsageDescription</key>
<string>说明使用关键通知的原因,比如:"此通知用于提醒您紧急任务,会突破静音模式"</string>

然后在请求通知权限时,必须包含.criticalAlert选项:

UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound, .criticalAlert]) { granted, error in
    if let error = error {
        print("权限请求失败:\(error.localizedDescription)")
    }
}

2. 补全通知请求的完整流程

你只创建了通知内容,还需要生成通知请求并提交给系统:

// 你的原有代码
let newNotification = UNMutableNotificationContent()
newNotification.title = "Taskko"
newNotification.body = textNotification
newNotification.sound = .defaultCritical
newNotification.badge = UserDefaults.standard.integer(forKey: "counterOfNotif") as NSNumber
newNotification.interruptionLevel = .critical

// 新增:创建并提交通知请求
let requestIdentifier = UUID().uuidString
// 若需延迟触发,可替换为UNTimeIntervalNotificationTrigger等类型的trigger
let request = UNNotificationRequest(identifier: requestIdentifier, content: newNotification, trigger: nil) 

UNUserNotificationCenter.current().add(request) { error in
    if let error = error {
        print("添加通知请求失败:\(error.localizedDescription)")
    }
}

3. 验证系统版本兼容性

interruptionLevel是iOS 15及以上才支持的API,如果设备系统版本低于iOS 15,这个属性会失效,需做版本判断:

if #available(iOS 15.0, *) {
    newNotification.interruptionLevel = .critical
} else {
    // iOS 15以下无法使用关键通知,可降级为普通通知
    newNotification.sound = .default
}

4. 检查设备设置

  • 确保设备未开启专注模式,或在专注模式设置中允许该应用的通知突破限制
  • 确认设备音频未完全静音(关键通知可突破静音,但部分场景仍需系统音频正常)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 15:00:07