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

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 14:40:06