iOSiOSCocoaObjective-CiOS 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)/FCM (Firebase 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.

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 up to 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, Android, and Windows 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.

Native PubNub Publish and Subscribe operation dictates that when a message is published by a client on a specific channel, all clients subscribing to that channel will receive that message.

When the Mobile Push Gateway is enabled, you may associate unique mobile devices (via their device push tokens) with PubNub channel names.  Once this association is made, when a message is published to a channel that has been associated with an GCM/FCM, APNS, or MPNS device, all associated GCM/FCM, APNS, or MPNS devices will receive that message via their associated (GCM/FCM, APNS, or MPNS) native service.

Behind the scenes, the PubNub Mobile Push Gateway establishes an authenticated connection to GCM/FCM, APNS, or MPNS service providers based on your registered configuration.

Device Connected
[currently subscribed]
Device Token/ID
Registered to Channel
Device Token/ID
Not Registered to Channel
App in ForegroundApp in BackgroundApp in ForegroundApp in Background
  • Receive Publish Directly
  • Push Notification Sent
  • Receive Push Notification
    Content [no UI notification]
[Android Only]
  • Receive Publish Directly
  • Push Notification Sent
  • Push Notification Received
    [with UI Notification]

[iOS]
  • Publish Not Received
  • Push Notification Sent
  • Push Notification Received
    [with UI Notification]
  • Receive Publish Directly
  • No Push Notification sent for this device
[Android Only]
  • Receive Publish Directly if subscribed in background
  • No Push Notification sent for this device

[iOS]
  • Publish Not Received
  • No Push Notification sent for this device
Device Disconnected
[not currently subscribed]
Device Token/ID
Registered to Channel
Device Token/ID
Not Registered to Channel
App in ForegroundApp in BackgroundApp in ForegroundApp in Background
  • Publish Not Received
  • Push Notification Sent
  • Receive Push Notification
    Content [no UI notification]
  • Publish Not Received
  • Push Notification Sent
  • Push Notification Received
    [with UI Notification]
  • Publish Not Received
  • No Push Notification sent for this device
  • Publish Not Received
  • No Push Notification sent for this device

Follow this for valid APNS provisioning on iOS as of iOS 9 and Xcode 7

  1. Open Keychain Access on your Mac.

  2. In top bar of Finder, select Keychain Access > Certificate Assistant > Request a Certificate From a Certificate Authority.

    Certificate Authority

  3. Fill in your email address and name on the following screen. Make sure to leave the CA email address blank and select Saved to disk.

    Certificate Information

  4. Click continue and save to desktop

    Certificate Assistant

  5. First open your Xcode project and navigate to general settings and build information for your project. Click on Capabilities

    General Settings

  6. Toggle the switch for Push Notifications to On

    Switch for Push Notifications

  7. Now we need to add your Push Certificate to your Apple Developer Account on the Developer Portal. Go to this address: https://developer.apple.com/account/

  8. On the left, under Identifiers, click on App IDs. Then select your app, which should be prepended with something along the lines of Xcode iOS App ID [bundle identifier]. Open this and click Edit at the bottom

    Bundle Identifier


    Bundle Identifier ID

  9. Now scroll down and make sure to select the box for Push Notifications and click Create Certificate...

    Create Certificate

  10. The next page brings up a dialog explaining the earlier steps in this tutorial, which we already completed. Click Continue

    Add iOS Certificate

  11. Now upload the certificate you saved to your desktop in Step 4

    Upload CSR File

  12. Your screen should look like this. Click Generate to move on

    Generate Certificate

  13. Now click Download to get that newly created certificate

    Download Certificate

  14. Open the newly downloaded certificate in Keychain Access. It should open in this program automatically if you double click it to open.

  15. Export the certificate (click on My Certificates in the left side bar of Keychain Access). Then right click on the certificate matching the name of your app, and click on Export.

    Keychain Access

  16. Save to desktop as my_cert.p12 (must be in .p12 format)

    Save to Desktop

  17. Now convert the certificate to my_cert.pem in preparation for uploading to PubNub with the following command:

          openssl pkcs12 -in my_cert.p12 -out my_cert.pem -nodes -clcerts
  18. Verify the cert was created correctly by running one of the following commands (depending on whether you are working with a development or production certificate):

          # For Development Certs
          openssl s_client -connect
            gateway.sandbox.push.apple.com:2195 -cert
            my_cert.pem -key my_cert.pem
          # For Production Certs
          openssl s_client -connect gateway.push.apple.com:2195
            -cert my_cert.pem -key my_cert.pem
  19. Upload the valid certificate to PubNub via https://admin.pubnub.com. Select your App on the Apps screen.

    Uploading Certificate

  20. Select your keys from the next screen.

  21. In the key options screen, upload my_cert.pem (make sure to select whether it is Development or Production). Note it is best practices to use a different set of PubNub keys for Production and Development.

    Mobile Push Portal

Visit Apple APNS docs to learn more about APNS and how it works.

APNS HTTP/2 apis are better than the old binary apis because the HTTP/2 apis due to its simple request/response like usage. There is no need to open multiple connections and listen to feedback connections in a separate process. The same connection can be used to send multiple push notifications and the feedback from a push notification comes back in the response.

Here is a little summary of the benefits of APNS HTTP/2 Token based push:

  • Request/Response (aka stream) for every sent (more reliable (e.g. JSON reason for a bad request or 410 if the token is invalid))
  • Allows instant feedback (no separate feedback service!), since details are on the HTTP/2 response
  • Multiplexing: multiple requests (to APNs) on a single connection
  • Binary
  • Simpler certificate handling: Just a single cert! (no separate for dev/prod, VOIP etc)
  • 4KB size of payload (for all versions of iOS/OSX), but just on the new HTTP/2 API

APNS HTTP/2 also supports the old style .pem cert based push mechanism, with the added advantage of not requiring to deal with out-of-band feedback. There is no extra setup needed from clients to enable this feature. PubNub can use a config flag on the client acct apns_http2_enable to enable this.

In order to support APNS HTTP/2 Token based API we will need the following information from client for each developer account:

  1. TEAM_ID= Team id of the app developer account

    AUTH_KEY_ID= key_id of the app developer account (kid)

    AUTH_KEY= encrypted authorization key generated from the app developer account in .P8 format

    "TEAM_ID": "7XP9D6K55Z",
    "AUTH_KEY_ID": "J9FYG7HYAP"
    "AUTH_KEY": "-----BEGIN PRIVATE KEY-----
    MIGTAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBHkwdwIBAQYHd68sd1e/YhTGaS5Y6PBlrWCmIc3YvWmxM9Gds7nJAsqgCgYIKoZIzj0DAQehRANCAAR63MArstzfQkH+ilMHF+sm5gpZNUIOnSKKv0Sak4u5nLQoLIlEFFwhlKctxISxF2pLi/JgHf0MZAlyanTGewSo
    -----END PRIVATE KEY-----"

In addition to the above information, APNS2 requires the apns_topic (BUNDLE_ID) for each app provided as part of the header.

Not supplying the apns_topics (BUNDLE_ID) in the header will get the 400, {"reason":"MissingTopic"} response from APNS.

Invalid apns_topic will get the 400: {"reason":"TopicDisallowed"} error response.

The BUNDLE_ID can be sent in one of two ways:

  1. As a parameter in the push payload:

    {
        "pn_apns": {
            "aps": {
                "alert": {
                    "body": "hello"
                }
            },
            "pn_bundle_ids": [
                "com.PubNub.TestPush",
                "com.Another.bundleId"
            ]
        }
    }

    The pn_bundle_ids parameter can be a single string value or a list of strings. pusher will send the push message to all the apps in the list.

    The client must supply valid bundle ids and manage the app bundle ids accordingly.

  2. Customer pre-provisions a single bundle_id on the acct and it will be used for all push messages for the account.

    This will work when client has only one app which they pre-provision or they send the same push to all their apps and they don't need to send meta parameter in each publish. PubNub will send the push notification to the bundle_id. Client will be responsible for maintaining the valid bundle_ids on the account.

    When there is a bundle_id listed in the meta parameter it takes precedence over the pre-provisioned bundle id.

Follow this for valid APNS provisioning on iOS as of iOS 9 and Xcode 7

  1. First open your Xcode project and navigate to general settings and build information for your project. Click on Capabilities

    General Settings

  2. Toggle the switch for Push Notifications to On

    Switch for Push Notifications

  3. Now we need to add your Push Certificate to your Apple Developer Account on the Developer Portal. Go to this address: https://developer.apple.com/account/

  4. Now click on Certificates, IDs & Profiles in the left hand index pane.

  5. Then click on Keys and add a new one by clicking on the + button in the upper right

    iOS Token keys-1

    iOS Token keys-2

  6. Select the APNs toggle on the key creation page and enter a name, like below:

    iOS Token Add keys

  7. Now hit Continue then select Confirm on the next page

    iOS Token Add keys confirmation

  8. Download your key and take note of the Key ID because you will need it for later. Also note that this is the only time you will be allowed to download this key. You will have to revoke it and generate a new one if you lose this copy.

    iOS Token keys view

  9. Now we need to get our Team ID by clicking on the name in the upper right, then selecting View Account

    iOS Token keys view account

  10. Take note of the Team ID on your account page:

    iOS Token Membership details

  11. Upload the valid token key file to PubNub via https://admin.pubnub.com. Select your App on the Apps screen.

    Uploading Certificate

  12. Select your keys from the next screen.

  13. Now update the Auth Key ID, Team ID, and upload the .p8 key file from earlier. Make sure to select Development or Production and if you want to include the Bundle ID of the app (or apps) you want to send push notifications to, you can include that now. This can also be included in publishes with push notifications.

    PubNub Dashboard Push service Settings

Visit Apple APNS docs to learn more about APNS and how it works.
To register for receipt of messages arriving on a PubNub channel to be forwarded to an Apple device via APNS, you must first retrieve that Apple device's unique ID, otherwise know as its device push token.
 
Device tokens can change, so your app needs to reregister every time it is launched.
Apple provides an excellent step-by-step walkthrough on how to achieve this, available from this link.
For convenience, we've also provided some code samples below for registering for both iOS10 only, and iOS10 & lower.
// Make sure to include this at the top of AppDelegate.m
@import UserNotifications;

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    // Check Notification Settings on launch
    [[UNUserNotificationCenter currentNotificationCenter] getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) {
        switch (settings.authorizationStatus) {
            // This means we have not yet asked for notification permissions
            case UNAuthorizationStatusNotDetermined:
            {
                [[UNUserNotificationCenter currentNotificationCenter] requestAuthorizationWithOptions:(UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionBadge) completionHandler:^(BOOL granted, NSError * _Nullable error) {
                    // You might want to remove this, or handle errors differently in production
                    NSAssert(error == nil, @"There should be no error");
                    if (granted) {
                        [[UIApplication sharedApplication] registerForRemoteNotifications];
                    }
                }];
            }
                break;
            // We are already authorized, so no need to ask
            case UNAuthorizationStatusAuthorized:
            {
                // Just try and register for remote notifications
                [[UIApplication sharedApplication] registerForRemoteNotifications];
            }
                break;
            // We are denied User Notifications
            case UNAuthorizationStatusDenied:
            {
                // Possibly display something to the user
                UIAlertController *useNotificationsController = [UIAlertController alertControllerWithTitle:@"Turn on notifications" message:@"This app needs notifications turned on for the best user experience" preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *goToSettingsAction = [UIAlertAction actionWithTitle:@"Go to settings" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    
                }];
                UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleDefault handler:nil];
                [useNotificationsController addAction:goToSettingsAction];
                [useNotificationsController addAction:cancelAction];
                [self.window.rootViewController presentViewController:useNotificationsController animated:true completion:nil];
                NSLog(@"We cannot use notifications because the user has denied permissions");
            }
                break;
        }
        
    }];
    
    return YES;
}
// Make sure to include this at the top of AppDelegate.m
@import UserNotifications;

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    // We want to check Notification Settings on launch.
    // First we must determine your iOS type:
    // Note this will only work for iOS 8 and up, if you require iOS 7 notifications then
    // contact support@pubnub.com with your request
    float systemVersion = [[[UIDevice currentDevice] systemVersion] floatValue];
    if (systemVersion >= 10) {
        [[UNUserNotificationCenter currentNotificationCenter] getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) {
            switch (settings.authorizationStatus) {
                    // This means we have not yet asked for notification permissions
                case UNAuthorizationStatusNotDetermined:
                {
                    [[UNUserNotificationCenter currentNotificationCenter] requestAuthorizationWithOptions:(UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionBadge) completionHandler:^(BOOL granted, NSError * _Nullable error) {
                        // You might want to remove this, or handle errors differently in production
                        NSAssert(error == nil, @"There should be no error");
                        if (granted) {
                            [[UIApplication sharedApplication] registerForRemoteNotifications];
                        }
                    }];
                }
                    break;
                    // We are already authorized, so no need to ask
                case UNAuthorizationStatusAuthorized:
                {
                    // Just try and register for remote notifications
                    [[UIApplication sharedApplication] registerForRemoteNotifications];
                }
                    break;
                    // We are denied User Notifications
                case UNAuthorizationStatusDenied:
                {
                    // Possibly display something to the user
                    UIAlertController *useNotificationsController = [UIAlertController alertControllerWithTitle:@"Turn on notifications" message:@"This app needs notifications turned on for the best user experience" preferredStyle:UIAlertControllerStyleAlert];
                    UIAlertAction *goToSettingsAction = [UIAlertAction actionWithTitle:@"Go to settings" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                        
                    }];
                    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleDefault handler:nil];
                    [useNotificationsController addAction:goToSettingsAction];
                    [useNotificationsController addAction:cancelAction];
                    [self.window.rootViewController presentViewController:useNotificationsController animated:true completion:nil];
                    NSLog(@"We cannot use notifications because the user has denied permissions");
                }
                    break;
            }
            
        }];
    } else if ((systemVersion < 10) || (systemVersion >= 8)) {
        UIUserNotificationType types = (UIUserNotificationTypeBadge | UIUserNotificationTypeSound |
                                        UIUserNotificationTypeAlert);
        UIUserNotificationSettings *mySettings = [UIUserNotificationSettings settingsForTypes:types categories:nil];
        
        [[UIApplication sharedApplication] registerUserNotificationSettings:mySettings];
    } else {
        NSLog(@"We cannot handle iOS 7 or lower in this example. Contact support@pubnub.com");
    }
    
    return YES;
}
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {

	NSLog(@"deviceToken: %@", deviceToken);
	[[NSUserDefaults standardUserDefaults] setObject:deviceToken forKey:@"DeviceToken"];
 }
    
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {

	NSLog(@"%s with error: %@", __PRETTY_FUNCTION__, error);
}
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
     
    [[NSUserDefaults standardUserDefaults] setObject:deviceToken forKey:@"DeviceToken"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}
[self.client addPushNotificationsOnChannels:@[@"apns"] withDevicePushToken:self.pushToken
							  andCompletion:^(PNAcknowledgmentStatus *status) {
    
 	if (!status.isError) {

		// Handle successful push notification enabling on passed channels.
	}
	else {

		/**
		 Handle modification error. Check 'category' property
		 to find out possible reason because of which request did fail.
		 Review 'errorData' property (which has PNErrorData data type) of status
		 object to get additional information about issue.

		 Request can be resent using: [status retry];
		 */
	}
}];
addPushNotificationsOnChannels and its variant methods associate a channel to a registration token.
[self.client addPushNotificationsOnChannels:@[@"wwdc",@"google.io"] 
					    withDevicePushToken:self.devicePushToken 
						      andCompletion:^(PNAcknowledgmentStatus *status) {

	if (!status.isError) {

	// Handle successful push notification enabling on passed channels.
	}
	else {

		/**
		 Handle modification error. Check 'category' property
		 to find out possible reason because of which request did fail.
		 Review 'errorData' property (which has PNErrorData data type) of status
		 object to get additional information about issue.

		 Request can be resent using: [status retry];
		 */
	}
}];
removePushNotificationsFromChannels and its variant methods disassociate a channel from a registration token.
[self.client removePushNotificationsFromChannels:@[@"wwdc",@"google.io"]
							 withDevicePushToken:self.devicePushToken
								   andCompletion:^(PNAcknowledgmentStatus *status) {

	if (!status.isError) {

		// Handle successful push notification disabling on passed channels.
	}
	else {

		/**
		 Handle modification error. Check 'category' property
		 to find out possible reason because of which request did fail.
		 Review 'errorData' property (which has PNErrorData data type) of status
		 object to get additional information about issue.

		 Request can be resent using: [status retry];
		 */
	}
}];
pushNotificationEnabledChannelsForDeviceWithPushToken lists channels registered to device token.
 [self.client pushNotificationEnabledChannelsForDeviceWithPushToken:self.devicePushToken
													  andCompletion:^(PNAPNSEnabledChannelsResult *result,
																	  PNErrorStatus *status) {
 	 if (!status) {

		// Handle downloaded list of channels using: result.data.channels
	}
	else {

		/**
		 Handle audition error. Check 'category' property
		 to find out possible reason because of which request did fail.
		 Review 'errorData' property (which has PNErrorData data type) of status
		 object to get additional information about issue.

		 Request can be resent using: [status retry];
		 */
	}
 }];
The equivalent method calls are also available via our Android, Objective-C, Swift, and .NET Mobile Gateway guides.
PubNub SDKs natively support associating device/registration tokens to channel names. To achieve this, they use a REST wrapper to add, remove, and list device registration IDs by channel.
The following serves as a REST request reference for adding, removing, and listing associated devices and channels. Whenever possible, use the native method call available in the SDK, instead of manually issuing the REST call.
http://pubsub.pubnub.com/v1/push/sub-key/<SUB_KEY>/devices/<REG_ID>?<OPERATION>=<CHANNEL_LIST>&type=<TYPE>
ParameterTypeRequiredDescription
OPERATION AND CHANNEL_LIST
OPERATION is one of add, list or remove. CHANNEL_LIST is a comma separated string of channels.
Optional
If not specified, defaults to the the list operation.
SUB_KEY
String
Yes
This is your PN API subscribeKey.
REG_ID
string
Yes
The device registraton ID.
TYPE
TYPE is one of gcm, apns, and mpns.
Optional
If no type specified, server will default to apns (for backwards compatibility)

[1, "Modified Channels"]
  • On success returns a 200 JSON Array of [1, "Modified Channels"].
  • On error returns 403 for PAM errors. Any status code other than 200 or 403 should be handled as fatal and retried at your discretion.
http://pubsub.pubnub.com/v1/push/sub-key/demo/devices/ALICE?type=gcm | apns | mpns &add=myCH
http://pubsub.pubnub.com/v1/push/sub-key/demo/devices/ALICE?type=gcm | apns | mpns&add=news,sports
http://pubsub.pubnub.com/v1/push/sub-key/demo/devices/ALICE?type=gcm | apns | mpns
http://pubsub.pubnub.com/v1/push/sub-key/demo/devices/ALICE?type=gcm | apns | mpns&remove=myCH
http://pubsub.pubnub.com/v1/push/sub-key/demo/devices/ALICE/remove?type=gcm | apns | mpns
Using a stock trading app use-case as an example, you may wish to send this stock alert to your users:
	{
		"name": "Fitchwitz Technology",
		"snapshot": {
			"last": 40.52,
			"volume": "3495345",
			"change": ["+4.02","+7.45%"]
		},
		"ticker": {
			"newsflash": [
				"Fitchwitz antivirals in the total number of shares being sold in the public offering have exercised in full.",
				"The offering price of all their option to purchase an additional zillion shares of its common stock is sweet.",
				"Offering is expected to occur today announced public offering when 100 shares went byebye."
			],
			"url": "http://FitchwitzTech.com/fooz"
		}
	}
This message is received, in its entirety, to all native PubNub client subscribers.
To make it properly formatted for receipt via APNS, we must add a pn_apns attribute to it, like so:
{
	"name" : "Fitchwitz Technology",
	"pn_apns" : {
		"aps" : {
			"alert" : "Fitchwitz Technology",
            "badge": 2,
            "summary_for_mobile": "Fitchwitz antivirals... more info at http://FitchwitzTech.com/fooz"
        }
    },
    "snapshot" : {
        "last" : 40.52,
        "volume" : "3495345",
        "change" : ["+4.02","+7.45%"]
    },
    "ticker" : {
        "newsflash" : [
	        "Fitchwitz antivirals in the total number of shares being sold in the public offering have exercised in full.",
	        "The offering price of all their option to purchase an additional zillion shares of its common stock is sweet.",
	        "Offering is expected to occur today announced public offering the offering when 100 shares went byebye."
        ],
        "url" : "http://FitchwitzTech.com/fooz"
    }
}
 
pn_apns must contain a dictionary of valid keys and values. pn_apns must begin with a sole aps child key, and cannot be a string, int, or array. For more info on proper formatting of your pn_apns payload, see Apple's reference.
After making these modifications to our message payload, upon publishing, this message will still be received in its entirety by all native PubNub client subscribers (including any pn_gcm, pn_apns, and pn_mpns contents), however, any devices registered to receive messages on the published channel via GCM/FCM, APNS, or MPNS will only receive the content contained within pn_gcm, pn_apns, or pn_mpns, respectively.
The following examples show how to publish to APNS devices with the PubNub Objective-C client:
NSDictionary *payloads = @{@"aps": @{@"alert":"To Apple and PN Native devices!"}};
[self.client publish:nil toChannel:channel mobilePushPayload: payloads
	  withCompletion:^(PNPublishStatus *status) {

	if (!status.isError) {

		// Message successfully published to specified channel.
	}
	else {

		/**
		 Handle message publish error. Check 'category' property to find 
		 out possible reason because of which request did fail.
		 Review 'errorData' property (which has PNErrorData data type) of status
		 object to get additional information about issue.

		 Request can be resent using: [status retry];
		 */
	}
}];
The JSON message published by the above looks would be:
{
    "pn_apns": {
        "aps": {
            "alert": "Only for Apple!"
        }
    }
}
NSDictionary *payloads = @{@"aps": @{@"alert":"To Apple and PN Native devices!"}};
[self.client publish: @{@"data":@"To PN Native devices only!"} toChannel:channel 
   mobilePushPayload: payloads withCompletion:^(PNPublishStatus *status) {

	if (!status.isError) {

		// Message successfully published to specified channel.
	}
	else {

		/**
		 Handle message publish error. Check 'category' property to find 
		 out possible reason because of which request did fail.
		 Review 'errorData' property (which has PNErrorData data type) of status
		 object to get additional information about issue.

		 Request can be resent using: [status retry];
		 */
	}
}];
The JSON message published by the above looks would be:
{
    "pn_apns": {
        "aps": {
            "alert": "To Apple and PN Native devices!"
        }
    },
    "data": "To PN Native devices only!"
}
Publishing using the above referenced dictionary structure, or via the literal JSON snippet, both have the same effect.

If you are interested in sending unique messages on a per-Mobile Gateway type in a single publish, just include all or some additional endpoint key (pn_apns, pn_gcm and pn_mpns) in your message.

Native PubNub devices will receive the ENTIRE message payload, but 3rd-Party endpoints by type will only receive the data encapsulated in their associated endpoint key.

In the below example:

  • Associated APNS devices will receive only the data within the pn_apns key.
  • Associated GCM/FCM devices will receive only the data within the pn_gcm key.
  • Associated MPNS devices will receive only the data within the pn_mpns key.
  • Native PubNub subscribers will receive the entire object literal, including the pn_apns, pn_gcm, pn_mpns, and full_gamekeys.
    {
        "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"
            }
        },
        "pn_mpns" : {
            "type" : "flip",
            "title" : "Front title",
            "count" : 1,
            "back_title" : "Back Tile",
            "back_content" : "Back message"
        },
        "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.

Yes, you can set an expiration time when publishing a push notification via APNS. Timeouts are measured in seconds (default is 3600, or 1 hour) and are set via the top level key of pn_ttl. For example, to set the timeout to 60 seconds (1 minute):

    {
        "pn_apns" : {
            "aps" : {
                "alert" : "You got mail."
            }
        },
        "pn_ttl" : 60
    }

Note that Apple will only queue a single message per device/app. For example, if you send 10 push notifications to a device that's powered off, then all notifications besides the last one are discarded, regardless of TTL.

Sometimes it is desirable to exclude a device from a group push notification. For example if a user has multiple devices registered to same channel and wants to send a group push notification he/she may want to not receive the same push on own devices. We support the pn_exceptions parameter in the payload to handle this. The pn_exceptions parameter accepts "device push tokens" (the same token used to register the device for push messages).

    {
        "pn_apns" : {
            "aps" : {
                "alert" : {
                    "body" : "hello"
                }
            },
            "pn_exceptions" : [
                "da284603e1e96ac453541cd1942659808a69c09fb1dbb2e3c11aba6cdcaec642"
            ]
        }
    }
    {
        "pn_apns" : {
            "aps" : {
                "alert" : {
                    "body" : "hello"
                }
            },
            "pn_exceptions" : [
                "5821e49019f3554872c3897dd800367bf803aa28871699b0e5960fba203446e9",
                "da284603e1e96ac453541cd1942659808a69c09fb1dbb2e3c11aba6cdcaec642"
            ]
        }
    }
    {
        "pn_gcm" : {
            "alert" : "hello",
            "pn_exceptions" : [
                "2643d955c7f2506e55f225b56da7eb8676cced80de93df51aad7569ee833b92f"
            ]
        }
    }
Inform customers of unregistered/inactive push devices via a webhook (similar to presence webhooks).
The following events will trigger the webhook. All errors should trigger immediately after a push (except for feedback which can happen after 5 minutes of a push).
  • Feedback -­ Apple feedback service ­- PubNub push server polls the feedback server after 5 minutes of a push to get list of inactive/uninstalled devices.
  • Remove - Invalid token error -­ Usually indicates when a sandbox token is used in production or vice versa.
  • Update -­ Canonical ID -­ The device has multiple tokens (old and new), replace the old token with new token.
  • Remove - NotRegistered - App was uninstalled or no longer configured for push notifications.
	HTTP POST
	Content­Type: application/json
	{
		"sub_key" : <sub­key>,
		"action" : <action contains extra details about how the device was removed ­ see events section>
		"device" : <device token>,
		"platform" : "apns|gcm|mpns",
		"timestamp" : <unix timestamp (utc) when the device was removed>
	}
An APNS device was uninstalled from feedback.
	{
		"sub_key" : "sub­c­e0d8405a­b823­11e2­89ba­02ee2ddab7fe",
		"action" : "feedback",
		"device" :"904181a3fc8bfaf95cc40551d81b5b8d0bd1d42c38b1e496648132a555325e8c",
		"platform" : "apns",
		"timestamp" : 1444241230
	}
A GCM/FCM device was updated from old token APA91bEgK4D to new token ta28zYhV.
	{
		"sub_key" : "sub­c­4745b1e4­19ba­11e4­bbbf­02ee2ddab7fe",
		"action" : "update",
		"old_device": "APA91bEgK4D"
		"device" : "ta28zYhV"
		"platform" : "gcm",
		"timestamp" : 1441230130
	}
A MPNS device was uninstalled.
	{
		"sub_key" : "sub­c­8a888f2c­d7a1­11e3­8c07­02ee2ddab7fe",
		"action" : "remove",
		"device" : "http://sn1.notify.live.net/throttledthirdparty/01.00/AQG2MdvoLlZFT7­VJ2TJ5LnbAgAAAAADAQAAAAQUZm52OkRFNzg2NTMxMzlFMEZFNkMFBlVTU0MwMQ"
		"platform" : "mpns",
		"timestamp" : 1400218910
	}
 
If a device has been registered to receive Mobile Push Gateway messages via GCM/FCM, APNS, or MPNS, and is also running a native PubNub Android, iOS, or Windows client SDK, and is natively subscribed to the same associated channel via the native PubNub client SDK, it will receive the message twice -- once via the Mobile Push Gateway, and once via the native PubNub client SDK. You will need to manually add logic to de-duplicate in this case.

If you are experiencing issues publishing to devices via the PubNub Mobile Gateway, the following are debug techniques that may help narrow down the issue. Each of them circumvents PubNub's Mobile Push Gateway logic to ensure that your device push tokens, applications, and registration/certificates are configured correctly.

If the following scripts are not working for you, then PubNub isn't a variable in the cause of the issue -- successful results with the below scripts script is a pre-requisite for PubNub Mobile Gatway logic to work.  Regardless if its a PubNub issue or not, we're always happy to help!  By getting us the results of the following tests when opening a support ticket, it may save a lot time isolating the root cause of your issue.

Use this script to publish a message to APNS, completely circumventing PubNub infrastructure. It requires an APNS certificate and an iOS device token.

Use the following curl command to publish a message to GCM/FCM, completely circumventing PubNub infrastructure. It requires a registration ID. Taken from Google's GCM/FCM page.

    curl --header "Authorization: key=<API_KEY>" \
        --header Content-Type:"application/json" \
        https://gcm-http.googleapis.com/gcm/send \
        -d "{\"registration_ids\":[\"ABC\"]}"

Use the following curl command to publish a message to MPNS, completely circumventing PubNub infrastructure. It requires a device push token.

    curl -v -H "Content-Type:text/xml" -H "X-WindowsPhone-Target:Toast" -H "X-NotificationClass:2" -X POST -d "<?xml version='1.0' encoding='utf-8'?><wp:Notification xmlns:wp='WPNotification'><wp:Toast><wp:Text1>My title</wp:Text1><wp:Text2>My subtitle</wp:Text2></wp:Toast></wp:Notification>" http://dm2.notify.live.net/throttledthirdparty/01.00/AQGiZ6EjjX0ySLELCr3iykPvAgAAAAADBAAAAAQUZm52OkRFNzg2NTMxMzlFMEZFNkMFBlVTU0MwMQ

You have implemented mobile push notifications into your PubNub application but now you are having some troubles. Maybe it's missing messages on client devices, getting duplicate messages, getting messages meant for another user/device. Whatever it is, we will provide the best tools and techniques for finding the root cause and resolving, or at least just getting all the necessary data points to send to PubNub Support to assist with troubleshooting.

You can do some high level debugging using the channel's -pndebug channel and checking to see if the device is still registered to the channel. Messages from -pndebug come from the APNS and GCM/FCM services (from Apple and Google, not PubNub). Here are the steps:

  1. Use the PubNub Debug Console to subscribe to the channel's -pndebug channel. If the channel you are publishing to is foo, then subscribe to foo-pndebug. Make sure you use the right pub/sub keys.
  2. Add 'pn_debug':true to your message payload at the top level.
        {
            "pn_gcm": {
                "data": {
                    "message": "hello"
                }
            },
            "pn_apns": {
                "aps": {
                    "alert": "hello"
                }
            },
            "pn_debug": true
        }
  3. Publish the message to channel foo, not to the channel's -pndebug channel. You can publish from your client or server application or from another instance of Debug Console (again, make sure you use the same pub/sub keys). You should see useful error messages in the Debug Console where you are subscribing to foo-pndebug, if there are any problems with the push message registration.

The following message shows how many devices successfully received the push notification that were registered for push messages on the target channel for each push service.

Devices found for push notification apns: 2 gcm: 3 mpns: 0

The following messages are examples of the types of messages that GCM/FCM and APNS push services can send back to PubNub's mobile push notification gateway servers.

    gcm Error: InvalidRegistration Devices: null
    gcm WARNING error: NotRegistered, sub_key: sub-c-..., channel: my_channel, reg_id: APA91bHRRxfHHB_T0AVojoJx..., timetoken: 14567269547473296
    apns INFO Certificate for sub-c-... valid (expiration: Sep 14 08:58:26 2016 GMT)
    apns ERROR Error on APNS send for subkey sub-c-... / channel gone_fishing / device 2a0a6234ffdb85df6624cf0546...: invalid token

All of the above messages can be sent to your server using PubNub's Mobile Push Gateway web hooks. A web hook is a URL (that you can have us configure on your keys) to a REST endpoint on your server. As messages come back to PubNub from the mobile push notification services, PubNub will relay them onto your REST endpoint for you to log and process as you require. Contact PubNub Support to request this configuration for your keys.

You can also check to see if the device is still registered to the channel after you publish the push notification using a simple REST URL in the browser.

  1. http://pubsub.pubnub.com/v1/push/sub-key/your_sub_key/devices/device_reg_token?type=push_type
  • where push_type is either gcm or apns
  • and device_reg_token is the device's registration token

This will return all channels the device is still registered for push notification for the push type provided.

Example of response:

["demo","demo1","demo2"]

If that list comes back empty then there was likely a device registration token issue (invalid token or device not registered, for example). This might happen because the device token was reported as invalid by the push notification services (APNS or GCM/FCM) and PubNub in turn unregisters that device token from all channels. But the -pndebug channel should reveal the reason for this to you.

Most times it is not PubNub that is causing the push notification issues. Often it is an invalid registration token (APNS or GCM/FCM) or a device with two valid registration tokens (yes, it can actually happen) or the push service cert or key is no longer valid. Testing push notifications without PubNub getting involved is the best way to eliminate, or hone in on, the area of probable fault.

There are a few good online tools for testing GCM/FCM push notifications and one native Mac app.

For APNS, you can run a simple Python script that uses your push certificate (.pem file) to verify that the certificate is valid. And optionally, you can specify a device registration token to which test push notifications will be sent. See our knowledge base article, How Do I Test My PEM Key, for full details.

For more rich UI/UX tools, you can find APNS test apps for the Mac (in the App Store) as well as online web apps:

See also:

  1. Apple Doc Troubleshooting Push Notifications

For additional platform and endpoint information, please see our detailed Android, Objective-C, Swift, and .NET Mobile Gateway guides.

 
The idea is to always check the validity of the APNS registration token with every cold start of the app, but only update PubNub's mobile push registration when the registration token actually changes for that device.

An often overlooked best practice when implementing Apple Push Notifications (APN) in your iOS applications is verifying that the registration token has not become invalid with each cold start of the app. A cold start happens when application didFinishLaunching is called (the actual method name is longer and spelled out in the docs linked below).

Here's the outline of what we need to do:

  • Call registerForRemoteNotification in didFinishLaunching. This will ask APNS for the registration token. The response is handled in application didRegisterForRemoteNotificationsWithDeviceToken.
  • In didRegisterForRemoteNotifications, you will receive the registration token.
  • Check for the current registration token in NSUserDefaults.
  • If the registration token from NSUserDefaults is nil or not equal to the registration token that was just passed into didRegisterForRemoteNotifications, then...
    • register for push notifications with PubNub using the new registration token
    • save the new registration token in NSUserDefaults
  • Otherwise, the registration token has not changed (is still valid), and you do not need to do anything further (you are already registered for push notifications on PubNub channels from the last cold start of the app).
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    PNConfiguration *configuration = [PNConfiguration configurationWithPublishKey:@"pub-c-..."
                                                                     subscribeKey:@"sub-c-..."]
    self.client = [PubNub clientWithConfiguration:configuration];
 
    UIUserNotificationType types = (UIUserNotificationTypeBadge | UIUserNotificationTypeSound | 
                                    UIUserNotificationTypeAlert);
 
    UIUserNotificationSettings *mySettings =
        [UIUserNotificationSettings settingsForTypes:types categories:nil];
 
    [[UIApplication sharedApplication] registerUserNotificationSettings:mySettings];
    [[UIApplication sharedApplication] registerForRemoteNotifications];
 
    return YES;
 }
 
- (void)application:(UIApplication *)application 
  didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
  
    NSData *oldToken = [[NSUserDefaults standardUserDefaults] dataForKey:@"DeviceToken"];
    if (oldToken && [oldToken isEqualToData:deviceToken]) {
        
        // registration token hasn't changed - carry on
        return;
    }
 
    // remove old token from all PubNub channels for push notifications
    [self.client removeAllPushNotificationsFromDeviceWithPushToken:oldToken
                                                     andCompletion:^(PNAcknowledgmentStatus *status) {
        
        NSLog(@"status: %@", status);
        // Check whether request successfully completed or not.
        // if (status.isError) // Handle modification error. 
        // Check 'category' property to find out possible issue because
        // of which request did fail. Request can be resent using: [status retry];
    }];
 
    [self.client addPushNotificationsOnChannels:@[<array of channels here>] 
                            withDevicePushToken:deviceToken andCompletion:^(PNAcknowledgmentStatus *status) {
                                      
        NSLog(@"status: %@", status);
        if (!status.isError) {
                
            [[NSUserDefaults standardUserDefaults] setObject:deviceToken forKey:@"DeviceToken"];
            [[NSUserDefaults standardUserDefaults] synchronize];
        }
        else {
        
            // Handle modification error. 
            // Check 'category' property to find out possible issue because
            // of which request did fail. Request can be resent using: [status retry];
        }
    }];
}

For more details (but less precise code example), please review the the PubNub iOS SDK Mobile Push Gateway documentation.