Swift 如何检测 App 是否由用户点击本地通知启动(含被杀死场景)
iOS 检测本地通知启动App的全场景解决方案
核心原因
当App处于**未运行(被用户手动杀死)**状态时,用户点击本地通知启动App的事件不会走userNotificationCenter(_:didReceive:withCompletionHandler:)回调,通知参数会通过启动选项传递给入口方法,需要单独兼容。
分步实现方案
1. 确认通知代理设置时机
你当前将UNUserNotificationCenter的代理设置在application(_:willFinishLaunchingWithOptions:)中的操作是正确的,确保在App启动最早阶段完成代理绑定,避免事件丢失。
2. 兼容未运行状态的通知启动检测
根据你的App架构选择对应处理方式:
场景A:使用AppDelegate(无SceneDelegate,iOS12及以下或手动关闭了Scene)
在application(_:didFinishLaunchingWithOptions:)中检查启动选项的本地通知参数:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // 检测是否由点击本地通知启动 if let localNotification = launchOptions?[.localNotification] as? UILocalNotification { // 此处处理通知对应的业务逻辑,比如跳转指定页面 processNotification(localNotification.userInfo) } return true }
场景B:使用SceneDelegate(iOS13+,Xcode13新建项目默认配置)
iOS13之后采用多场景架构,启动参数需要在SceneDelegate的入口方法中检测:
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { // 检测是否由点击本地通知启动 if let notificationResponse = connectionOptions.notificationResponse { let userInfo = notificationResponse.notification.request.content.userInfo // 此处处理通知对应的业务逻辑 processNotification(userInfo) } }
3. 保留原有存活状态的通知回调
保留你原有的userNotificationCenter(_:didReceive:withCompletionHandler:)实现,用来处理App处于前台、后台存活状态时的通知点击事件:
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { let userInfo = response.notification.request.content.userInfo // 此处处理通知对应的业务逻辑 processNotification(userInfo) completionHandler() }
注意事项
你可以将通知的业务处理逻辑封装为统一的processNotification(_ userInfo: [AnyHashable: Any]?)方法,避免两种场景下重复写逻辑。
内容的提问来源于stack exchange,提问作者Marin
相关产品推荐
相关产品推荐

