stackerleet stackerleet - 4 years ago 142
Swift Question

Why is the payload in the push notification nil?

I have data saved to the push notification using Parse.com's Push Service, but when I print the payload. It appears to be nil. Why is this occurring, and how do I fix this? Thanks. Any help is appreciated.

func pushNotifications(){

let data = [
"alert" : "\(username!) wants you to listen to \(titleofsong) by \(artist)",
"identifier":"PlayerController", "title" : "test title", "artist" : "test artist"
]
let push = PFPush()
push.setQuery(pushQuery)
push.setData(data)
push.sendPushInBackgroundWithBlock {
success, error in

if success {
print("The push succeeded.")
} else {
print("The push failed.")
}
}
}

func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
PFPush.handlePush(userInfo)
let title = userInfo["aps"]!["title"]
let artist = userInfo["aps"]!["artist"]
print(title)
print(artist)
}

Answer Source

According the documentation your APNS payload is supposed to look like

let data = [
  "aps" : [
    "alert" : [
      "title" : "New Request",
      "body" : "\(username!) wants you to listen to \(titleofsong) by \(artist)",
      "action-loc-key" : "Listen"
    ],
  ],
  "username" : "test user",
  "identifier" : "PlayerController",
  "title" : "test title",
  "artist" : "test artist"
]

Then you can extract title and artist with

let title = userInfo["title"]
let artist = userInfo["artist"]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download