iOS Mobile Push Gateway Tutorial for Realtime Apps

 

Requires that the Push Notifications add-on is enabled for your key. How do I enable add-on features for my keys? - see http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys

PubNub's Mobile Push Gateway feature enables developers to bridge native PubNub publishing with 3rd-party push notification services including Google Android GCM (Google Cloud Messaging), Apple iOS APNS (Apple Push Notification Service), and Microsoft Windows Phone MPNS (Microsoft Push Notification Service).

By using the Mobile Push Gateway, developers can eliminate the need for developing, configuring, and maintaining additional server-side components for 3rd-party push notification providers.

When to use Native PubNub Messaging vs PubNub Mobile Push Gateway to 3rd-Party Messaging Services

For mission critical messaging, PubNub recommends implementing PubNub native messaging functionality. PubNub native messaging touts a low-latency, bi-directional notification solution that can be delivered to any mobile device, secure, access restricted, and encrypted message payloads of 32KB, and the ability to recover missed messages with Storage & Playback (history) APIs.

Despite the advantages of the native PubNub approach, there are cases where a developer may choose to utilize a 3rd-party notification system, for example, when migrating existing applications already utilizing 3rd-party notification systems to PubNub native messaging. On iOS applications where running in the background is not an option, the Mobile Push Gateway provides a method to send messages quickly and reliably via PubNub whether or not the application is in the foreground or background.

When publishing a message associated with an APNS deviceID, the message is sent to all PubNub native subscribers listening on that channel. For example, if you have native PubNub Python, Ruby, and JavaScript subscribers listening on channel "foo", and you've previoulsy associated channel "foo" with APNS deviceIDs abc, and xyz, when you publish "hello world" to channel "foo", it will be received by the PubNub native Python, Ruby, and JavaScript subscribers.

In addition, the portion of the message encapsulated within a "pn_apns" attribute, containing a valid APNS object messaging format (see below), will also be forwarded to Apple's APNS gateway, where it will be sent via APNS to Apple devices with APNS deviceIDs abc and xyz.

Behind the scenes, the PubNub Mobile Push Gateway establishes an authenticated connection to the Apple APNS service based on the application's configured Apple Push Certificate (which the developer has uploaded to the PubNub Admin Console). Assuming this certificate, and application are configured correctly for Push Notifications, and the deviceID has been associated with the PubNub channel the message was published on, Apple will accept the APNS message for delivery.

PubNub supports both PushKit APNS and VoIP push notifications. Apple Push Notification services require that a Push Certificate (APNS or VoIP) be generated that uniquely identifies your PubNub enabled application to the APN service. This Push Certificate is uploaded to PubNub in the PubNub Admin Portal and is used to form a secure connection to the APN service.

Additional information on creating and verifying your certificate can be found at https://github.com/pubnub/objective-c/tree/v3.7.11/iOS/create_and_verify_apns.md.

Similarly, a Device Token is created for each client iOS device that registers with Apple to receive push notifications. The Device Token is analogous to a phone number; it contains information that enables APNs to locate the device on which the client application is installed.

Before you can push APNS messages natively through Apple, or through PubNub, you must first define an App ID and create a PEM Certificate file. http://code.google.com/p/apns-php/wiki/CertificateCreation#Generate_a_Push_Certificate depicts a quick summary of the steps.

Verify your development cert was created correctly by running this command (replace with your key/cert name):

openssl s_client -connect gateway.sandbox.push.apple.com:2195 -cert server_certificates_bundle_sandbox.pem -key server_certificates_bundle_sandbox.pem

To verify production certs, replace gateway.sandbox.push.apple.com with gateway.push.apple.com (remove the sandbox portion of the name). Once they are verified, upload them to the PubNub Admin Console's Mobile Push Gateway configuration.

In addition to the above steps, We also provide a step-by-step video tutorial of the process:

Two files referenced from the video, generateAPNSPemKey.sh and verifyCertWithApple.sh are also available in our Github repo. The Final product is available here: HOWTO/APNSVideo

Normally, messages published to PubNub Reatime Network are only accessible by native PubNub subscribers, routed by subscribe key and channel name. When messages are published to a PubNub channel associated with the APNS Device Token, the Device Token is used to identify which devices should receive the message as a push notification. The Device token is combined with the published message and this Notification Package is sent from PubNub Mobile Push Gateway to the APN service.

Apple enforces that both APNS Push Certificates and Device Tokens must be created and used separately for Development and Production environments.

A notification is a short message consisting of two major pieces of data: the Device Token and the Payload. The Apple Notification Payload contains information about how the system should alert the user as well as any custom data you provide.

 
As noted on Apple's Developer site here

Each remote notification includes a payload. The payload contains information about how the system should alert the user as well as any custom data you provide. In iOS 8 and later, the maximum size allowed for a notification payload is 2 kilobytes; Apple Push Notification service refuses any notification that exceeds this limit. (Prior to iOS 8 and in OS X, the maximum payload size is 256 bytes.)

The forementioned site also continues to explain that: Each notification payload is composed of a JSON dictionary object (as defined by link: RFC 4627). This dictionary must contain another dictionary identified by the key aps. The aps dictionary contains one or more properties that specify the following actions:

  • An alert message to display to the user
  • A number to badge the application icon with
  • A sound to play

The following JSON messages detail the structure the PubNub Mobile Push Gateway expects to properly route a message to a channel associated with an APNS deviceID.

For the most simple test, you can send a simple String, such as hello world from any PubNub publishing entity, including the PubNub Developer Console available at http://www.pubnub.com/console:

When sending the above string to a channel associated with an iOS DeviceID, if everything is in place, the device should display "hello world" when the application is in the background. You should only send strings to test connectivity; once you've verified connectivity, send notifications in object format which can contain alert, badge count, and sound data:

{
	"pn_apns": {
		"aps": {
			"alert": "This is a push notification",
			"badge": 9,
			"sound": "bingbong.aiff"
		}
	}
}

Its critical that the above structure be followed. Apple will drop any messages destined for APNS that do not follow the forementioned object structure.

Before you can push GCM messages natively through Google, or through PubNub, you must first setup your GCM configuration.

Once you've obtained the API Key, login to the PubNub Admin Console, and scroll down to Push Notifications → Google Cloud Messaging and click on "Add" to add your API Key. http://developer.android.com/google/gcm/gs.html provides additional information about this process.

When publishing a message associated with an GCM deviceID, the message is sent to all PubNub native subscribers listening on that channel. For example, if you have native PubNub Python, Ruby, and JavaScript subscribers listening on channel foo, and you've previoulsy associated channel foo with GCM RegistrationIDs abc, and xyz, when you publish hello world to channel foo, it will be received by the PubNub native Python, Ruby, and JavaScript subscribers.

In addition, the portion of the message encapsulated within a pn_gcm attribute, containing a valid GCM object messaging format (see below), will also be forwarded to Googles's GCM gateway, where it will be sent via GCM to Android devices with GCM RegistrationIDs abc and xyz.

Behind the scenes, the PubNub Mobile Push Gateway establishes an authenticated connection to the Google GCM service based on the application's configured GCM API Key (which the developer has uploaded to the PubNub Admin Console). Assuming this API key, and application are configured correctly for Push Notifications, and the RegistrationID has been associated with the PubNub channel the message was published on, Google will accept the GCM message for delivery.

This key is used by Google to authenticate your application for accounting purposes. This key is uploaded to the PubNub Administrator Console upon configuring your PubNub account to enable Mobile Push Gateway.

The first time an Android application needs to use the GCM service, it must call the GoogleCloudMessaging method register() which should return a Registration ID. This Registration ID is then associated with one or more channels. The Android application should store this ID for later use (for instance, to check in onCreate() if it is already registered.

The Sender ID is created during the GCM registration process ( Sender ID is your GCM Project Number ) and is used to permit PubNub Mobile Push Gateway push notification messages to be sent to the Android device via GCM.

When sending the following object to a channel associated with a GCM Registration ID, if everything is in place, the device should receive the object {"summary":"hello world"} when the application is in the background or foreground.

{
    "pn_gcm": {
        "data" : {
            "summary": "hello world"
        }
    }
}

This dictionary must contain another dictionary identified by the key pn_gcm. When sending a message to GCM you must use the data parameter to include a message payload.

It is possible to structure a single message to contain different message payloads for native PubNub and multiple 3rd-Party endpoints. To do this, just specify root-level pn_apns, pn_gcm and pn_mpns keys with appropriate platform-specific data. Its important to remember that Native PubNub devices will receive the ENTIRE payload, but 3rd-Party endpoints will only receive the data encapsulated in their associated pn_* key.

In the below example, associated iOS devices will receive only the data within the pn_apns key, and associated GCM devices will receive only the data within the pn_gcm key. Native PubNub subscribers will receive the entire literal object, including pn_apns, pn_gcm and full_game keys.

{
    "pn_apns": {
        "aps" : {
            "alert": "Game update 49ers touchdown",
            "badge": 2
        },
        "teams" : ["49ers", "raiders"],
        "score" : [7, 0]
    },
    "pn_gcm": {
        "data" : {
            "summary": "Game update 49ers touchdown",
            "teams" : ["49ers", "raiders"],
            "score" : [7, 0],
            "lastplay" : "5yd run up the middle"
        }
    },
    "full_game" : {
        "date" : "2014.05.20",
        "foobar" : "Data that is not pertinent to devices"
    }
}

For any given published message, you may include any combination of pn_* and non-pn_* keys and data.

To modify associations between a channel and an APNS or GCM Device ID, use the .mobile_gw_provision() method:

    pubnub.mobile_gw_provision ({
         device_id: 'A655FBA9931AB',
         op       : 'add', // or 'remove'
         gw_type  : 'apns', // or 'gcm'
         channel  : 'my_chat',
         callback : mySuccessCallback,
         error    : myErrorCallback,
    });

After successfully associating device IDs with channels, publishing messages in the correct formats to those channels will result in all associated devices receiving the 3rd-party notifications.


Check out PubNub's other Objective-C-based SDKs, such as iOS, Cocoa.