Swift iOS 如何实现闹钟/WhatsApp来电样式的通知
实现持久闹钟/来电类通知的配置方案
当前代码生成的通知属于系统默认的临时横幅,受系统展示策略限制会在数秒后自动收起,按照下面的方法调整就能实现不自动消失、类似系统闹钟/WhatsApp来电的通知效果。
本地通知调整步骤
- 核心优先级配置
给通知内容设置interruptionLevel属性为.timeSensitive,这是让通知不自动消失的核心配置:
该属性对应通知的系统优先级,设置为timeSensitive后,通知会以顶部横幅形式常驻展示,直到用户手动关闭或操作,完全不会自动定时收起;如果要达到系统闹钟的最高展示级别,可以设置为
.critical,该级别可以绕过系统静音模式(需要向苹果申请特殊权限)。
- 注册带交互的通知分类
要实现类似闹钟的“稍后提醒”“关闭”操作按钮,需要在App启动阶段提前注册通知分类:
// 在App启动回调中执行注册逻辑 let snoozeAction = UNNotificationAction(identifier: "snooze", title: "稍后提醒", options: []) let dismissAction = UNNotificationAction(identifier: "dismiss", title: "关闭", options: [.destructive]) let alarmCategory = UNNotificationCategory( identifier: "alarm_category", actions: [snoozeAction, dismissAction], intentIdentifiers: [], options: [] ) UNUserNotificationCenter.current().setNotificationCategories([alarmCategory])
- 改造现有通知构造代码
在原有实现基础上补充核心配置项:
func onTest() { let content = UNMutableNotificationContent() content.title = "Weekly Staff Meeting" content.body = "Every Tuesday at 2pm" // 新增核心配置 content.interruptionLevel = .timeSensitive content.categoryIdentifier = "alarm_category" content.sound = .default var dateComponents = DateComponents() dateComponents.calendar = Calendar.current dateComponents.hour = 16 dateComponents.minute = 11 let trigger = UNCalendarNotificationTrigger( dateMatching: dateComponents, repeats: true ) let uuidString = UUID().uuidString let request = UNNotificationRequest( identifier: uuidString, content: content, trigger: trigger ) let notificationCenter = UNUserNotificationCenter.current() notificationCenter.add(request) { error in if error != nil { // 处理调度错误 } } }
FCM远程通知适配
- 服务端下发通知payload时,需要在
aps字段中补充interruption-level: "time-sensitive"参数,客户端收到后就会按照持久横幅样式自动展示,不会触发5秒自动消失的逻辑。 - 如果需要给远程通知绑定自定义操作按钮,需要让FCM下发静默通知,在客户端收到通知后手动构造带分类、优先级的UNNotificationContent再展示,不能直接使用FCM的自动展示逻辑。
前台通知展示配置
如果需要App在前台运行时也弹出不自动消失的通知横幅,需要实现通知代理方法:
extension NotificationManager: UNUserNotificationCenterDelegate { func userNotificationCenter( _ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void ) { completionHandler([.banner, .sound, .badge, .list]) } }
想要完全匹配WhatsApp来电的全屏通知效果,需要使用CallKit框架构建来电通知流程,这是苹果官方推荐的来电类通知实现方案,普通UNNotification无法实现系统级的全屏来电弹窗效果。
内容的提问来源于stack exchange,提问作者zidniryi
相关产品推荐
相关产品推荐

