0

Getting this data back as a notification and want to read it into usable variable types. I got all of them to work but the rewards and aps

    %@ [AnyHashable("description"): Open 10 common chests.,     AnyHashable("icon"):     localhost:8000//media/achievements/Common%20Chest%20Go-    Getter/bomb.jpg, AnyHashable("name"): Common Chest Go-Getter,     AnyHashable("gcm.message_id"):1486597426811663%bf6da727bf.   6da727, AnyHashable("rewards"): {"Battle helm":1,"Gems":1000}, AnyHashable("aps"): {
    alert = "Achievement Completed";
}]

So how do convert that to a usable variable?

    AnyHashable("rewards"): {"Battle helm":1,"Gems":1000},     AnyHashable("aps"): {
    alert = "Achievement Completed";
}

The returned item is called userInfo so like...

let rewards = userInfo["rewards"] as! [String:Int] 

Doesn't work, any help on this would be greatly appreciated! Again I'm in swift 3.0 so swift 3.0 examples could help.

svelandiag
  • 4,231
  • 1
  • 36
  • 72
Chrisman
  • 3
  • 1

1 Answers1

1

the notification userInfo is parsed as a Dictionary<String, Any> or [String: Any]

let userInfo: [String: Any] = [
    "description": "Open 10 common chests.",
    "icon": "localhost:8000//media/achievements/Common%20Chest%20Go-    Getter/bomb.jpg",
    "name": "Common Chest Go-Getter",
    "gcm.message_id": "1486597426811663%bf6da727bf.   6da727",

    "rewards": [
      "Battle helm": 1,
      "Gems":1000
    ],
    "aps": [
      "alert": "Achievement Completed"
    ]
]

if let rewards = userInfo["rewards"] as? [String: Any] {

  if let battle = rewards["Battle helm"] as? Int {
    print(battle) // 1
  }

  if let gems = rewards["Gems"] as? Int {
    print(gems) // 1000
  }

}

if let aps = userInfo["aps"] as? [String: Any] {

  if let alert = aps["alert"] as? String {
    print(alert) // Achievement Completed
  }

}

Looks like you are confused with this:

let arrayOfStrings = [String]()
let dictionary = [String: Any]()

let arrayOfDictionaries = [[String:Any]]()
Wilson
  • 9,006
  • 3
  • 42
  • 46