watchOS应用处于前台时本地通知不显示的问题求助
watchOS应用前台无法显示通知的解决方案
你的watchOS应用后台能正常展示通知,但前台无法弹出,核心是前台通知需要通过UNUserNotificationCenterDelegate的willPresent方法明确指定展示规则。结合你的代码,以下是具体修复方案:
1. 移除重复的通知请求代码
你的通知调度代码中重复调用了UNUserNotificationCenter.current().add(request),这会生成重复的通知请求,属于无效冗余代码,需删除其中一次:
// Schedule notification let content = UNMutableNotificationContent() content.title = "Exposure complete!" content.sound = UNNotificationSound.default let trigger = UNTimeIntervalNotificationTrigger(timeInterval: Double(exposure), repeats: false) let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger) let center = UNUserNotificationCenter.current() center.add(request) { error in if let error = error { print("Error scheduling notification: \(error)") } }
2. 确保Delegate正确生效
虽然你已在applicationDidFinishLaunching中设置了delegate,但可通过提前初始化的方式确保其生效,避免时机问题:
import WatchKit import UserNotifications class WatchDelegate: NSObject, WKApplicationDelegate { override init() { super.init() // 提前设置delegate,确保初始化时就绑定 UNUserNotificationCenter.current().delegate = self } func applicationDidFinishLaunching() { requestNotificationAuthorization() } private func requestNotificationAuthorization() { let center = UNUserNotificationCenter.current() center.requestAuthorization(options: [.alert, .sound, .badge]) { granted, error in if let error = error { print("Error requesting notification authorization: \(error)") } else { print("Notification authorization granted: \(granted)") // 额外验证当前权限状态 center.getNotificationSettings { settings in print("Current notification status: \(settings.authorizationStatus)") } } } } } extension WatchDelegate: UNUserNotificationCenterDelegate { func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { print("willPresent fired from watch delegate") // 明确指定前台展示的通知类型 completionHandler([.alert, .sound]) } }
3. 测试验证要点
- 测试时确保应用处于前台活跃状态(非后台/锁定屏幕)
- 若使用
UNTimeIntervalNotificationTrigger,建议设置较短的时间间隔(如5秒),便于快速验证 - 查看控制台输出,确认
willPresent fired from watch delegate是否打印,以此判断delegate是否正常触发
内容的提问来源于stack exchange,提问作者Joe Scotto
相关产品推荐
相关产品推荐

