tylerl
tylerl

Reputation: 1180

PhoneGap PushPlugin - Access iOS APNS Payload?

Using PushPlugin with my PhoneGap 3 iOS app, I've got push notifications mostly working, but I'm sending notifications to APNS with a custom payload. This is what it looks like:

$body = array(
    'customID' => $customID
);
$body['aps'] = array(
    'alert' => $message,
    'sound' => 'default'
);

From what I've read, this is supposed to be supported by APNS (scroll down to the bottom), but PushPlugin's documentation doesn't tackle iOS very well at all. What I want is to be able to access customID as a JS variable when my app is opened up by tapping on the notifications. When the app is simply launched on its own, I don't want anything special to happen. Moreover, it matters which notification the user tapped on - the customID is unique and important. I'm just really confused as I couldn't find anyone talking about handling these custom APNS payloads with PushPlugin.

Upvotes: 2

Views: 2439

Answers (2)

Mobiletainment
Mobiletainment

Reputation: 23261

The correct way of adding your custom variables to the push notification payload is not to by adding it to the aps namespace (this one is reserved by Apple), but separately, like:

$body['aps'] = array(
    'alert' => $message,
    'sound' => 'default'
);

$body['payload'] = array(
    'customID' => $customID
);

Within PhoneGap, you can then read it within your notification callback (e.g. onNotificationAPN) like so:

function onNotificationAPN (e) {
    if (e.customID)
    {
        navigator.notification.alert("CustomID: " + e.customID);
    }

Upvotes: 2

Eran
Eran

Reputation: 393781

I've never worked with PushPlugin, but looking at their code, I can point you in the right direction.

In the AppDelegate they pass the dictionary that contains the notification payload to an instance of the PushPlugin object and call the notificationReceived method of that instance.

notificationReceived of PushPlugin constructs a JSON string from that dictionary and passes it to the JS callback method that handles the notification.

Here is the example for the callback method from the PushPlugin docs:

function onNotificationAPN (event) {
    if ( event.alert )
    {
        navigator.notification.alert(event.alert);
    }

    if ( event.sound )
    {
        var snd = new Media(event.sound);
        snd.play();
    }

    if ( event.badge )
    {
        pushNotification.setApplicationIconBadgeNumber(successHandler, errorHandler, event.badge);
    }
}

I'm not very fluent in JavaScript, but event should contain the JSON string with all the data of the notification payload, including your custom property. You should be able to access it there.

Upvotes: 1

Related Questions