iOS应用运行时检测推送通知点击而非自动触发didReceiveRemoteNotification
解决应用运行状态下检测通知点击的问题
嘿,我完全懂你的痛点——didReceiveRemoteNotification在应用前台运行时会自动触发,但你只想在用户主动点击通知的时候才执行对应逻辑对吧?下面分iOS版本给你清晰的实现方案:
iOS 10 及以上版本(推荐使用)
从iOS 10开始,苹果引入了UserNotifications框架,专门拆分了「通知到达」和「用户点击通知」的回调,完美解决你的需求:
步骤1:注册通知权限并设置Delegate
在AppDelegate的didFinishLaunchingWithOptions方法中完成权限请求和Delegate绑定:
import UserNotifications func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // 请求通知权限(按需调整选项) UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { granted, error in guard granted else { return } DispatchQueue.main.async { UIApplication.shared.registerForRemoteNotifications() } } // 设置通知中心的Delegate,确保能收到回调 UNUserNotificationCenter.current().delegate = self return true }
步骤2:实现Delegate方法区分通知到达和点击
通过两个不同的Delegate方法分别处理「通知前台到达」和「用户点击通知」:
extension AppDelegate: UNUserNotificationCenterDelegate { // 👉 应用前台运行时,通知到达的回调(用户未点击,仅通知推送过来) func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { // 如果不想在前台显示通知,就传[];如果需要显示,传[.alert, .sound, .badge] completionHandler([]) } // 👉 用户点击通知的回调(无论应用是前台、后台还是未运行状态) func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { // 这里写用户点击通知后要执行的逻辑 let notificationContent = response.notification.request.content print("用户点击了通知,内容: \(notificationContent.body),附加信息: \(notificationContent.userInfo)") // 必须调用completionHandler结束回调 completionHandler() } }
iOS 10 以下版本(兼容旧系统)
对于iOS 10之前的系统,只能通过判断应用状态来区分「自动触发」和「用户点击」:
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) { if application.applicationState == .active { // 应用处于前台,是通知自动触发,跳过点击逻辑 completionHandler(.noData) return } // 应用处于后台或未运行,是用户点击通知进入应用,执行点击逻辑 print("用户点击了通知,附加信息: \(userInfo)") completionHandler(.noData) }
注意:iOS 10以下,应用前台运行时通知不会弹出通知栏,用户根本无法点击前台的通知,所以只需要在非活跃状态下处理逻辑即可。
内容的提问来源于stack exchange,提问作者Karan Alangat
相关产品推荐
相关产品推荐

