如何在watchOS下用SwiftUI实现闹钟的持续震动弹窗效果
核心问题解答
你询问的这个界面是watchOS为带自定义操作的时间敏感通知提供的全屏默认展示样式,属于UserNotifications框架的标准输出形态,并不是自定义的Alert组件。
复现该效果的具体步骤
- 第一步:申请对应权限并注册通知分类
你需要先在Watch App Extension代码中请求用户通知授权,同时注册你需要的两个自定义操作按钮:
import UserNotifications let notifyCenter = UNUserNotificationCenter.current() // 请求通知权限,需要持续唤醒的闹钟建议同时申请criticalAlert权限以绕过勿扰模式 notifyCenter.requestAuthorization(options: [.alert, .sound, .criticalAlert]) { granted, error in // 此处处理授权结果逻辑 } // 注册自定义操作和通知分类 let openAction = UNNotificationAction(identifier: "open_alarm", title: "Open", options: [.foreground]) let stopAction = UNNotificationAction(identifier: "stop_alarm", title: "Stop", options: [.destructive]) let alarmCategory = UNNotificationCategory(identifier: "alarm_notify", actions: [openAction, stopAction], intentIdentifiers: [], options: []) notifyCenter.setNotificationCategories([alarmCategory])
- 第二步:创建闹钟本地通知
设置通知的中断级别为时间敏感级,搭配你需要的闹钟音效即可:
let content = UNMutableNotificationContent() content.title = "闹钟提醒" content.body = "到设定的唤醒时间了" content.sound = UNNotificationSound(named: UNNotificationSoundName("your_alarm_sound.caf")) content.categoryIdentifier = "alarm_notify" // 时间敏感级别可以保证通知优先展示,设置为critical则可以绕过勿扰/静音模式 content.interruptionLevel = .timeSensitive // 示例设置为5分钟后触发闹钟,你可以替换为你需要的触发规则 let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 300, repeats: false) let request = UNNotificationRequest(identifier: "your_alarm_id", content: content, trigger: trigger) notifyCenter.add(request)
- 第三步:持续震动的逻辑实现
当你设置的高优先级通知触发后,watchOS会自动按照你配置的音效长度循环播放音效+震动,直到用户点击Stop/Open按钮为止,不需要你手动调用WKInterfaceDevice的play方法循环触发,系统会自动处理持续提醒逻辑。
如果你的App需要在前台运行时也展示相同效果,可以自行实现一个全屏的SwiftUI Sheet,模拟系统样式,同时循环调用震动和播放音效即可。
内容的提问来源于stack exchange,提问作者Loppik
相关产品推荐
相关产品推荐

