ios - 在 Swift 中访问 userInfo 字典

标签 ios swift dictionary parse-platform notifications

我正在尝试访问 application:didReceiveRemoteNotification() 中的 userInfo 字典,以便我可以根据收到的推送类型/如果有的话选择一个 segue收到推送。我已经尝试过这两种方式(我敢肯定,还有其他一些方式,我现在不记得了)。

if let info = userInfo as? Dictionary<String,String> {
        var notificationType = info["notificationType"]
}


if let info: String = userInfo["notificationType"] as? String {
        //do stuff
}

我没有收到任何错误,我只是什么都没收到。如果我打印 userInfo 字典,它只有一个成员 ["aps"],它包含显示给用户的推送消息,所以即使我只能访问它,我也可以有条件地使用它。

我尝试按照 Parse API 写入 userData:

let data = ["notificationType" : "coffee"]
push.setData(data)

所以一个问题是这似乎没有设置任何内容,但更大的问题是我无法获取任何 userInfo 数据。

你如何访问这本词典?

编辑

一些打印语句结果:

println(userInfo["aps"]) => {alert = "You've Been Invited To A Coffee Order";}

println(userInfo) => [aps: {alert = "You've Been Invited To A Coffee Order";}, type: coffee]

println(userInfo[0]) => nil

let info = userInfo as? Dictionary<String,String>
println(info) => nil

所以似乎只是警报键卡在了这个'aps' 数组中?字典?我没有创建它,它只是自动成为 userInfo

的一部分

编辑2

这是我设置数据和发送推送的代码。我从这里发送出现在 userInfo 中的数据:

func notifyUserOfCoffeeOrder(){
    var uQuery:PFQuery = PFUser.query()
    uQuery.whereKey("username", equalTo: usernameLabel.text)

    var pushQuery:PFQuery = PFInstallation.query()
    pushQuery.whereKey("user", matchesQuery: uQuery)

    var push:PFPush = PFPush()
    push.setQuery(pushQuery)
    let data = ["type" : "coffee",
                "alert" : "You've Been Invited To A Coffee Order"]
    push.setData(data)
    push.sendPush(nil)
    println("push sent")

}

这是 AppDelegate.swift 的整个函数,我从中提取接收到的数据:

func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
     NSNotificationCenter.defaultCenter().postNotificationName("getMessage", object: nil)

    if  let info = userInfo["type"] as? String {
        self.window = UIWindow(frame: UIScreen.mainScreen().bounds)

        var storyboard = UIStoryboard(name: "Main", bundle: nil)

        var initialViewController = storyboard.instantiateViewControllerWithIdentifier("coffeeVC") as UIViewController

        self.window?.rootViewController = initialViewController
        self.window?.makeKeyAndVisible()
    }

}

最佳答案

EDIT: I've know rebuilt this answer to conform with the comments given. Do note that I do not have access to Apples Push Notification services currently, and as such can't test this in the same environment as OP

似乎 APN(或 parse.com)在您构建时向 userInfo 中添加了一些内容。因此,我最好的建议是使用如下代码打印您收到的双字典中的所有内容。我还在此处提供了代码来解包在您在字典中查找内容时出现的可选值。

所以这是我修改后的示例代码:

func myApplicationFunc(didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
    // NSNotificationCenter.defaultCenter().postNotificationName("getMessage", object: nil)

    // Default printout of userInfo
    println("All of userInfo:\n\( userInfo)\n")

    // Print all of userInfo
    for (key, value) in userInfo {
        println("userInfo: \(key) —> value = \(value)")
    }

    if let info = userInfo["aps"] as? Dictionary<String, AnyObject> {
        // Default printout of info = userInfo["aps"]
        println("All of info: \n\(info)\n")

        for (key, value) in info {
            println("APS: \(key) —> \(value)")
        }


        if  let myType = info["type"] as? String {
            // Printout of (userInfo["aps"])["type"]
            println("\nFrom APS-dictionary with key \"type\":  \( myType)")

            // Do your stuff?
        }
    }
}

var userInfo : [ NSObject: AnyObject] =
[
    "aps" : [
        "alert" : "Coffee is not the answer",
        "type" : "coffee"
    ],
    "anotherType" : 123
]

myApplicationFunc(didReceiveRemoteNotification: userInfo)

此代码产生以下输出:

All of userInfo:
[anotherType: 123, aps: {
    alert = "Coffee is not the answer";
    type = coffee;
}]

userInfo: anotherType —> value = 123
userInfo: aps —> value = {
    alert = "Coffee is not the answer";
    type = coffee;
}

All of info: 
[alert: Coffee is not the answer, type: coffee]

APS: alert —> Coffee is not the answer
APS: type —> coffee

From APS-dictionary with key "type":  coffee

您应该能够在您的 application(...) 方法中添加我的代码,希望您能了解如何解包双字典,以及哪些信息实际上是转移给你。

附言!在这个answer to another post谈论他的 setMessage 如何干扰他的 setData,如果有一些代码影响你的结果,这可能也很有趣。仍然是我的示例代码,应该列出 userInfo

中收到的所有内容

关于ios - 在 Swift 中访问 userInfo 字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28951338/

相关文章:

用于复杂设计和架构的 IOS 静态库

ios - Realm :在不更新现有子对象的情况下更新/设置关系

swift - 如何检查用户的电子邮件是否已验证?

python - 更新字典中多个键值对的性能

java - 我如何将字符串和对象的映射转换为字符串和列表的映射

ios - 我如何强制 iOS MapKit 对其所有通信使用 HTTPS?

iOS 如何在使用 AVAssetWriter 捕获视频时正确处理方向

swift - 如何访问 [UIApplicationOpenURLOptionsKey : Any] in Swift 4? 的值

python - 格式化字典打印输出

ios - 使用 PKRevealController 时在前 View 上推送新 View