【问题标题】:How to get userInfo JSON Value inside didReceiveRemoteNotification如何在 didReceiveRemoteNotification 中获取 userInfo JSON 值
【发布时间】:2025-12-14 06:20:22
【问题描述】:
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject])
{
        PFPush.handlePush(userInfo)

        if application.applicationState == UIApplicationState.Active
        {
            PFAnalytics.trackAppOpenedWithRemoteNotificationPayload(userInfo)

            if let msg = userInfo["test"] as? Dictionary<String,AnyObject>
            {
                print(msg)
            }
        }

我的 userInfo["test"] JSON 值为:

> Printing description of userInfo:
▿ 3 elements
  ▿ [0] : 2 elements
    - .0 : message
    - .1 : 1235
  ▿ [1] : 2 elements
    - .0 : aps
    - .1 : 0 elements
  ▿ [2] : 2 elements
    - .0 : link
    - .1 : 

我可以获取我的 userInfo 数据,但我不知道为什么我的 msg 没有任何价值(甚至没有 nil 只是没有可显示的内容) 我怎么才能到 print(msg) ?

更新

这是我的推送:

$this->parsepush->send(array("channels" => ['test'], "data" => > $post_data));

在 $post_data 示例中:

$post_data = json_encode(数组 ('link' => $link, 'message' => $message));\

我已经尝试过来自的指令,但我也无法进行简单的打印。

get Value from userInfo

编辑

仍然跳过了“aps”部分。

Picture 1

我的 JSON

这是我的Json 的样子:

> {  
  "aps":{  
     "alert":{  
        "title":"$title",
        "body":"$message"
     },
     "badge":"1"
  },
  "adira":{  
     "link":"$link"
  }
}

这是我的代码:

>   func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
              //  PFPush.handlePush(userInfo)
       // PFAnalytics.trackAppOpenedWithRemoteNotificationPayload(userInfo)
        if let msg = userInfo["message"] as? String {
            print(msg)
            print("a")
        }     
        if let alertDict = userInfo["aps"]?["alert"] as? Dictionary<String, String> {
            print("title : ", alertDict["title"])
            print("body :", alertDict["body"]!)
            print("badge: ", alertDict["badge"]!)
            print("b")
        }      
        if let link = userInfo["link"] as? String {
            print(link)
            print("c")
        }
    }
}

但我仍然无法获取我的aps 数据。仍然为零或一无所有。

如果你想要一个特定的代码,只需点击下面的链接:

Full code AppDelegate.swift

编辑 2

我直接使用 print(userInfo) 打印输出是:

对象已保存。 [消息:iOS推送,aps:{},链接:]

更新 2

我尝试从 parse.com 推送,而不是我的网站(第 3 方)。 这就是我从普通打印(userInfo)中得到的

> [aps: {
    alert = 12345abc;
    sound = default;
}]

所以我想我会更改并在我的 JSON 中添加一些内容从我的网站到:

[aps:{
   alert = $message;
   sound = default;
   link = $link;
}]

类似的东西?

【问题讨论】:

  • 好吧,test 键没有任何价值,只有 messageapslink。请附上您发送的内容。
  • @jcaron 这里是我从网站$this-&gt;parsepush-&gt;send(array( "channels" =&gt; ['test'], "data" =&gt; $post_data )); 推送的内容所以我可以将 JSON 转换为 Dictionary 吗?还是字符串?
  • 不要在 cmets 中添加代码,编辑您的问题以添加代码。此外,您实际上没有包括您发送的内容 ($post_data)。你收到的 JSON 已经被 iOS 解码了,但是你还没有告诉我们你发送的 JSON 是什么。
  • 好的,抱歉,我会修复它。 @jcaron
  • 这是更新,该功能是使用 parse.com 监听来自我的网络服务的推送通知。我的网络服务使用 JSON 格式来推送它的数据,使用 2 个元素:(“消息”和“链接”),链接可以为空。 userInfo 已经正确接受了打印的数据,现在我需要提取消息数据(例如:“1235”,就像上面的数据一样),所以我可以使用它来创建一个带有该数据标题的通知(“1235”)我我的推送也更新了@jcaron

标签: ios json swift swift2


【解决方案1】:

如 cmets 中所述,APNS 有效负载中没有密钥 test
如果保证始终发送键 message 的值,您可以轻松解开该值

let msg = userInfo["message"] as! String
print(msg)

否则使用可选绑定

if let msg = userInfo["message"] as? String {
    print(msg)
}

要从aps 键获取alert 字典并打印例如body 字符串使用

if let aps = userInfo["aps"] as? [String:Any],
   let alertDict = aps["alert"] as? [String:String] {
    print("body :", alertDict["body"]!)
}

【讨论】:

  • 是的,非常感谢您,这很有效,但是我尝试了与“aps”相同的方法,但它不起作用,只是跳过但它适用于“消息”和“链接”。任何的想法? @vadian
  • 仍然跳过了那个 aps 部分。我已经上传了图片@vadian
  • 您的 JSON 值转储表明 aps 键包含 0 elements 又名空字典。
  • 如果我的aps这样声明{"aps":{"alert":"Testmessage","badge":"1"}}是对还是错? @vadian
  • alert 必须是具有特定键的字典:{"aps":{"alert":{"title":"TestTitle,"body":"Testmessage"},"badge": "1"}}。请阅读文档如何创建有效载荷developer.apple.com/library/ios/documentation/…
【解决方案2】:

我使用 APNs Provider 和 json payload 如下

{
  "aps" : {
    "alert" : {
      "title" : "I am title",
      "body" : "message body."
    },
  "sound" : "default",
  "badge" : 1
  }
}

由于提供者将其作为 JSON 定义的字典生成,iOS 将其转换为 NSDictionary 对象,没有 Dictionary 之类的下标,但可以使用 value(forKey:)

来自here的参考

这是我为 Swift 4 设计的方式

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
    guard application.applicationState == .active else { return }
    guard let alertDict = ((userInfo["aps"] as? NSDictionary)?.value(forKey: "alert")) as? NSDictionary,
        let title = alertDict["title"] as? String,
        let body = alertDict["body"] as? String
        else { return }
    let alertController = UIAlertController(title: title, message: body, preferredStyle: .alert)
    let okAct = UIAlertAction(title: "Ok", style: .default, handler: nil)
    alertController.addAction(okAct)
    self.window?.rootViewController?.present(alertController, animated: true, completion: nil)
    completionHandler(UIBackgroundFetchResult.noData)
}

【讨论】: