iOS APNS标准推送负载格式咨询:自定义数据放置位置疑问
APNS推送负载自定义数据的正确格式与数据获取方案
嘿,作为iOS新手碰到这个推送数据的问题太正常了,我来帮你把这个事儿捋明白~
首先明确标准格式
Apple的APNS官方规范里,自定义数据必须放在aps字典的外面,也就是你贴的第二个示例是完全符合标准的:
{ "aps": { "content-available":1, "alert": { "title": "Game Request", "body": "Bob wants to play poker" }, "sound": "default" }, "data": { "alertType": "ALERT", "eventTime": "121346666545454", "deviceId": "657585685858", "user":"Arun" } }
你之前把data放在aps里能拿到数据,是因为APNS并没有严格拦截aps里的额外字段,但这属于非标准用法,后续Apple如果调整推送校验规则,这种格式可能会出问题,所以强烈建议遵循官方规范。
为什么放外面点击通知启动拿不到数据?
这不是格式的问题,而是你没在正确的回调方法里读取推送数据!不同场景下,获取推送数据的入口不一样:
场景1:应用在后台/前台运行时收到推送
如果你用的是iOS 10及以上版本,推荐使用UNUserNotificationCenterDelegate的回调:
// 导入UserNotifications框架 import UserNotifications // 注册代理 UNUserNotificationCenter.current().delegate = self // 处理前台收到的推送 func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { let userInfo = notification.request.content.userInfo // 从userInfo里取出自定义data if let data = userInfo["data"] as? [String: Any] { print("拿到自定义数据:\(data)") } completionHandler([.banner, .sound]) } // 处理后台点击通知的情况 func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { let userInfo = response.notification.request.content.userInfo if let data = userInfo["data"] as? [String: Any] { print("点击通知拿到自定义数据:\(data)") } completionHandler() }
场景2:应用完全退出,点击通知启动
这种情况要在AppDelegate的启动方法里读取launchOptions:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // 检查是否是通过点击推送启动的 if let remoteNotification = launchOptions?[.remoteNotification] as? [String: Any] { if let data = remoteNotification["data"] as? [String: Any] { print("启动时拿到自定义数据:\(data)") } } return true }
总结
- 一定要遵循官方规范,把自定义数据放在
aps外面; - 根据应用的不同状态(前台/后台/已退出),在对应的回调方法里读取推送的
userInfo,就能正确拿到你的自定义data了。
内容的提问来源于stack exchange,提问作者Arun
相关产品推荐
相关产品推荐

