Swift中本地通知触发执行代码无响应,该如何解决?
问题分析与修复步骤
你遗漏了三个关键环节,导致通知显示时的代码无法触发执行:
1. 协议方法签名不匹配
你实现的userNotificationCenter(center:willPresent:withCompletionHandler:)和userNotificationCenter(center:didReceive:withCompletionHandler:)方法签名不符合UNUserNotificationCenterDelegate的规范,系统无法识别并调用这些方法。正确的方法需要省略第一个参数的标签(添加下划线_)。
2. 未设置通知中心的代理实例
你创建了MyUserNotificationCenterDelegate类,但没有将其实例绑定到UNUserNotificationCenter的delegate属性上,同时需要在视图中持有该实例的强引用,避免其被提前释放。
3. willPresent方法未实现核心逻辑
这个方法是处理应用前台状态下通知显示的回调,你留空了它——既没有添加要执行的代码,也没有调用completionHandler指定通知的展示选项,导致通知无法正常弹出,代码自然也不会执行。
修改后的完整代码
import SwiftUI import UserNotifications class MyUserNotificationCenterDelegate : NSObject, UNUserNotificationCenterDelegate { // 修正方法签名,添加下划线以匹配协议要求 func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { // 在这里添加你要执行的代码,比如控制台打印 print("通知已显示在屏幕上(无需用户交互)") // 指定通知展示选项,确保前台能弹出通知 completionHandler([.alert, .sound]) } // 修正方法签名,添加下划线以匹配协议要求 func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { print("用户点击了通知") completionHandler() } } struct ContentView: View { // 持有代理实例,避免被内存释放 private let notificationDelegate = MyUserNotificationCenterDelegate() var body: some View { VStack { Button("Permission") { UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { success, error in if success { print("授权成功!") } else if let error = error { print(error.localizedDescription) } } } Button("Schedule") { let content = UNMutableNotificationContent() content.title = "通知标题" content.subtitle = "通知副标题" content.sound = UNNotificationSound.defaultCritical let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 10, repeats: false) let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger) UNUserNotificationCenter.current().add(request) } Button("Stop") { UNUserNotificationCenter.current().removeAllPendingNotificationRequests() } } .onAppear { // 将代理实例绑定到通知中心 UNUserNotificationCenter.current().delegate = notificationDelegate } } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } }
内容的提问来源于stack exchange,提问作者codebreaker
相关产品推荐
相关产品推荐

