iOS关闭App后点击推送通知无响应问题排查求助
问题
App处于关闭状态时,点击推送通知后没有输出预期的app opened from PushNotification tap 2日志;但App在后台模式时,点击通知能正常输出app opened from PushNotification tap 1日志。请问遗漏了什么配置或代码?是否只有我遇到这个问题?
提供的代码
ContentView代码
import SwiftUI import UserNotifications struct ContentView: View { var body: some View { VStack { Button("Request Permission") { UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { success, error in if success { print("Success") } else if let error = error { print(error.localizedDescription) } } } Button("Schedule Notification") { let content = UNMutableNotificationContent() content.title = "Title" content.subtitle = "Subtitle" content.sound = UNNotificationSound.default let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false) let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger) UNUserNotificationCenter.current().add(request) } } } }
AppDelegate代码
class AppDelegate: NSObject, UIApplicationDelegate, UNUserNotificationCenterDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool { UNUserNotificationCenter.current().delegate = self return true } func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { print("app opened from PushNotification tap 1") completionHandler() } func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { print("app opened from PushNotification tap 2") completionHandler([.banner, .sound, .badge]) } }
原因及解决方案
你混淆了两个通知代理方法的触发场景:
userNotificationCenter:willPresent:withCompletionHandler:仅在App处于前台运行状态时被调用,作用是处理通知到达时的展示逻辑(比如是否显示横幅、播放声音),和点击通知打开App的操作无关,所以永远不会在App关闭/后台时点击通知触发。userNotificationCenter:didReceive:withCompletionHandler:才是处理用户点击通知的回调,无论App是后台状态还是完全关闭状态,只要用户点击通知打开App,这个方法都会被调用。
另外需要确认一个关键配置:在SwiftUI的App入口中,必须通过UIApplicationDelegateAdaptor关联你的AppDelegate,否则代理方法不会生效。示例如下:
@main struct YourAppName: App { @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate var body: some Scene { WindowGroup { ContentView() } } }
如果已经正确关联了AppDelegate,那问题就出在对两个代理方法的功能误解上,调整日志输出的位置即可:把"app opened from PushNotification tap 2"的逻辑移到didReceive response方法中,或者修正日志描述以匹配方法的实际作用。
内容的提问来源于stack exchange,提问作者Sergei Kirasirov
相关产品推荐
相关产品推荐

