企业级应用如何在非userDidRespondToPush方法中获取APNs用户信息
解决APNs推送信息获取问题:点击应用图标启动时提取用户信息
嘿,这个场景我做企业级应用的时候刚好碰到过,给你几个靠谱的方案,完美覆盖用户直接点击图标启动应用的情况:
核心方案:获取已送达的未处理通知(iOS 10+ 推荐)
从iOS 10开始,Apple推出的UNUserNotificationCenter框架提供了非常实用的API,其中getDeliveredNotifications(completionHandler:)能直接获取当前所有推送到设备、但还没被用户清除或处理的通知。你可以在应用启动的入口(比如AppDelegate的didFinishLaunchingWithOptions或者SceneDelegate的willConnectTo)调用这个方法,遍历通知数组提取需要的用户信息。
代码示例(Swift):
import UserNotifications func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // 确保已申请并获取远程通知权限(如果还没配置的话) UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { granted, error in if granted { DispatchQueue.main.async { application.registerForRemoteNotifications() } } } // 获取所有已送达的未处理通知 UNUserNotificationCenter.current().getDeliveredNotifications { notifications in guard !notifications.isEmpty else { return } for notification in notifications { let pushUserInfo = notification.request.content.userInfo // 根据你的推送payload格式提取用户信息 if let userProfile = pushUserInfo["user_info"] as? [String: String] { // 执行你的业务逻辑,比如缓存用户信息、跳转对应页面等 print("提取到用户信息:\(userProfile)") } } // 处理完后可以按需清除通知记录和角标,避免重复处理 let notificationIds = notifications.map { $0.request.identifier } UNUserNotificationCenter.current().removeDeliveredNotifications(withIdentifiers: notificationIds) application.applicationIconBadgeNumber = 0 } return true }
补充:覆盖点击通知启动的场景
如果用户是直接点击通知横幅/弹窗启动应用,你还可以通过启动选项launchOptions里的UIApplication.LaunchOptionsKey.remoteNotification获取推送信息,把这个逻辑和上面的方案结合,就能覆盖所有启动场景:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // 检查是否通过点击通知启动应用 if let pushPayload = launchOptions?[.remoteNotification] as? [String: Any] { let userInfo = pushPayload // 执行用户信息处理逻辑 } // 加上上面的getDeliveredNotifications逻辑 // ... return true }
注意事项
- 确保你的推送payload里包含需要的用户信息字段,并且格式符合预期;
- 处理完通知后记得清除对应的通知记录和应用角标,避免下次启动重复处理;
- iOS 10之前的旧API(比如
application(_:didReceiveRemoteNotification:))已经被弃用,建议全面迁移到UNUserNotificationCenter的API。
内容的提问来源于stack exchange,提问作者Bill Norman
相关产品推荐
相关产品推荐

