gpt4 book ai didi

Ios Swift 解码从 GCM 通知发送的 json 数据

转载 作者:行者123 更新时间:2023-11-29 11:58:25 24 4
gpt4 key购买 nike

我正在接收 GCM Json 编码的数据作为 AnyObject,如下所示

[MsgKey: {"NamKey":"Bdy","MobKey":"9964120147","UidKey":"Uid31"}, collapse_key: do_not_collapse, from: 925652137353]

我想解码上面的内容并将其传递给本地通知屏幕

我在下面试过:

func application(appPsgVar: UIApplication,
didReceiveRemoteNotification userInfo: [NSObject : AnyObject])
{
print("Notification: ",userInfo["MsgKey"]!)

let MsgVar = userInfo["MsgKey"]

var GotVar = MsgVar?.objectAtIndex(2)
|Or|
var GotVar = MsgVar?.objectForKey("UidKey")
|Or|
var GotVar = MsgVar?.valueForKey("UidKey")

    if let MsgVar = userInfo["MsgKey"] as? [String:AnyObject]
{
GetNfnFnc(MsgVar["NamKey"] as! String)
}

    if let MsgVar = userInfo["MsgKey"] as? NSData
{
var JsnAryVar: AnyObject!
do
{
JsnAryVar = try NSJSONSerialization.JSONObjectWithData(MsgVar, options: [])
print(JsnAryVar)
}
catch
{
print("ErrVar")
}

GetNfnFnc(JsnAryVar["NamKey"] as! String)
}
}

userInfo["MsgKey"] 给了我以下数据,但无法理解如何进一步解码

{"NamKey":"Bdy","MobKey":"9964120147","UidKey":"Uid31"}

最佳答案

实际问题是来自服务器的 Json 编码数据以字符串形式出现

方法 1:Eric D 建议并提供解决方案链接 Retrieving values from 2D array in JSON string

do
{
if let MsgCodVar = MsgSrgVar.dataUsingEncoding(NSUTF8StringEncoding),
let MsgJsnVar = try! NSJSONSerialization.JSONObjectWithData(MsgCodVar, options: []) as? [String:AnyObject]
{
print(MsgJsnVar)
}
}

方法 2:我自己的艰难解决方法 :-(

创建自己的函数将字符串数据转换为数组[String:AnyObject]

func CnvJsnSrgTooAryFnc(JsnSrgPsgVar: String) -> [String:AnyObject]
{
var JsnSrgVar = JsnSrgPsgVar
JsnSrgVar = JsnSrgVar.stringByReplacingOccurrencesOfString("\"", withString: "")
JsnSrgVar = JsnSrgVar.stringByReplacingOccurrencesOfString("{", withString: "")
JsnSrgVar = JsnSrgVar.stringByReplacingOccurrencesOfString("}", withString: "")
let SrgAryVar = JsnSrgVar.componentsSeparatedByString(",")

var JsnAryVar = [String:AnyObject]()
for SrgIdxVar in SrgAryVar
{
let SrgIdxAryVar = SrgIdxVar.componentsSeparatedByString(":")
JsnAryVar[SrgIdxAryVar[0]] = SrgIdxAryVar[1]
}
return JsnAryVar
}

let MsgAryVar = CnvJsnSrgTooAryFnc(MsgSrgVar)

MsgAryVar["UidKey"]

得到输出:

print(MsgSrgVar) :
{"NamKey":"Bdy","MobKey":"9964120147","UidKey":"Uid99"}

print(MsgAryVar)
["NamKey": Bdy, "MobKey": 9964120147, "UidKey": Uid99]

关于Ios Swift 解码从 GCM 通知发送的 json 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38133099/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com