iOS Push Notification

Push Notification helps you in sending event or alert to your app users even when they are not logged into app. App42 uses APNS (Apple Push Notification Service) to send Push Notification on iOS devices.

To configure Push Notifications for iOS Apps/Games, the prerequisites are :

bullet An iOS Developer Program membership on iOS Dev Center

bullet An iPhone/iPad.

bullet A Server, and this is where App42 Push Service comes into the picture.

Once you have all, you need to generate AppID and SSL certificate on iOS Developer portal, .p12 file and a provisioning profile configured for push notification. This guide will walk you through all the necessary steps needed to configure your app for push notification.

1. Generating Certificate Signing Request

To manually generate the certificate, Certificate Signing Request (CSR) file is needed from your MAC that will be used to authenticate the creation of SSL certificate.

To create CSR file, please follow the steps mentioned below:

bullet Open Keychain Access(Applications->Utilities->Keychain Access)

bullet Choose the menu option “Keychain Access -> Certificate Assistant -> Request a Certificate From a Certificate Authority…” and make sure no private key is selected in the main Keychain Access window.

RequestCSR

bullet Enter your Email Address and Common Name and check Saved to disk and click Continue to save it to your prefered location.

CertficateAssistant

2. Creating App ID

To install an application on your device, you need to create an App ID and you do this on iOS Dev Center .

bullet Login and select Certificates, Identifiers & Profiles .

DeveloperResource

bullet Select Identifiers in the presented screen :

Identifiers

bullet Click on the + button at the upper right corner of the presented screen:

AppIds

bullet Enter the name for new AppID under App ID Description.

bullet Select App ID Prefix.

bullet Select Explicit App ID option under App ID Suffix and enter the Bundle ID.

AppIDDescription

bullet Enable Push Notification for this App ID by selecting the checkbox next to Push Notifications under App Services.

bullet Select Continue and Confirm all the details are correct in the presented screen such as App ID description, Bundle Identifier and Push Notifications Checkbox and Select Submit button to finish the App ID creation.

AppServices

3. Creating SSL Certificate

Now we will generate SSL certificate that is needed to make a secure connection between the App42 Push Server and APNS. This certificate will be linked to the App ID you just created so that the App42 Server will send push notifications to this particular app only.

bullet Select App IDs under Identifiers that shows list of app ids and select your newly created App ID i.e. App42PushApp.

AppIDSelection

bullet Select Edit button in the presented screen.

EditAppID

bullet Scroll down to Push Notifications to create SSL certificate.

bullet Select Create Certificate under Development SSL Certificate as we are creating for development environment.

CreateCertificate

bullet Next you will be guided to Add iOS Certificate screen where you will be asked to create Certificate Signing Request(CSR) that we have created already under Section-1 and hence Select Continue.

AddiOSCertificate

bullet Next you will be asked to upload the CSR file. Select the Choose File and browse to .certSigningRequest file and Click Open then Click Generate to generate the SSL certificate.

UploadCSR

bullet It may take few seconds to generate the certificate. Once generated, click Download to download the certificate. I recommend to store all the generated files in the single folder as it will be easy to locate the files later.

DownloadCertificate

Now you have a valid certificate for sending push notification in development environment, If you need this for Production environment, repeat the same process for the Production.

4. Creating .p12 file:

bullet Now locate the SSL certificate file that you just downloaded and double click to install it to your Keychain Access.

bullet Now Open Keychain Access -> My Certificates(Under Category section)and Right Click on the certificate you just installed and choose Export.

ExportCertificate

bullet Enter the filename and select the location to save and click Save.

p12

bullet Enter the export Password when asked. You may be asked to enter your system account password to allow Keychain Access to export the certificate from your Keychain.

bullet Make your .p12 file compatible with APP42 server by following the below mentioned steps:

a. Keep your .cer file and .p12 file in a single folder

b. Open terminal and go to the folder that has both the files $ cd “your folder path”

c. Now execute the following commands in the terminal :




openssl x509 -in aps_development.cer -inform DER -out developer_identity.pem -outform PEM

openssl pkcs12 -nocerts -in App42PushDevKey.p12 -out App42PushDevKey.pem

openssl pkcs12 -export -inkey App42PushDevKey.pem -in developer_identity.pem -out iphone_dev.p12

Where, aps_development.cer <= SSL Certificate you downloaded from Apple in Step 3 and App42PushDevKey.p12 <= The .p12 file you just created above.

5. Generating the Provisioning Profile

Go to iOS Dev Center and select Certificates, Identifiers & Profiles . Select Provisioning Profile option from the sidebar and select + button.

ProvisionalProfile

Now you have to follow a 4-step Add iOS Provisioning Profile wizard

Step-1 : Select Type

Select iOS App Development under Development and then click Continue.

ProfileTypeSelection

Step-2 : Configure

Select the App ID you created earlier in section-2 of this tutorial for me it is “App42PushApp” and click Continue.

ProvisionAppID

Step-2.1 Select Certificates :

Select the certificates from the list provided to include in this provisional profile and click Continue.

SelectCertificate

Step-2.2 Select Devices :

Select the devices you wish to include in this provisioning profile and click Continue.

SelectDevices

Step-3 : Generate

Enter a meaningful name for this provisioning profile in field Profile Name.This will be used to identify the profile in the portal. Now click Generate.

GenerateProfile

Step-4 : Download

Select Download to download the generated profile. Add the profile to Xcode by double clicking on it and You are done.

DownloadProfile

Note:- Repeat the process to generate the Ad Hoc / App Store profile, the only difference is, select the Select Type as Ad Hoc / App Store instead of Development in the Step-1.

6. Configuring your App42 Cloud API App for Push Notification

To send Push Notification using App42 Cloud API, you have to upload the iphone_dev.p12 file, that you created in step-4, to AppHQ Console.

bullet Register with App42 platform

bullet Create an app once you are on Quick-start page after registration.

bullet If you are already registered, login to AppHQ console , create an app from App Manager -> App Create link and select Push Notification in AppHQ Menu.

bullet Select iOS settings in Settings.

bullet Select your App Name from the drop down menu.

bullet Browse your iphone_dev.p12 file by clicking ‘choose file’ option to upload the file.

bullet Enter password given during creation of the iphone_dev.p12 file.

bullet Select the development environment from the drop down menu.

bullet Click on the submit button and it’s done here.

UploadP12

Repeat the same process to configure App42 Cloud API App for Push when it is ready for distribution, except selecting production environment for Environment option from the drop down menu.

Note:- Environment drop-down menu has two options development and production. You can upload two .p12 files one for each environment. But we recommend to have only one active push profile at a time.

MultipleP12

7. Configuring Your iOS Application for Push Notification

bullet We have encapsulated all the code written below in a sample project. Download the Sample from our GitHub Repo and unzip it.

bullet Open Xcode project and go to Constants.h file in which you need to pass the required information like API KEY & SECRET KEY which you have received after the success of app creation from AppHQ Console.

7.1 Xcode settings to enable iOS Application for Push Notification:

bullet In order to configure your app for Push Notification, we need to modify Bundle Identifier and Code Signing as per the Provisional Profile we installed earlier.

bullet Open your Xcode project and select info.plist file under Supporting Files in the left-hand-side menu. Change the Bundle Identifier same as App ID’s Bundle Identifier , for me it is com.shephertz.app42pushapp.

XcodeBundleIdentifier

bullet Select the project file in the left-hand-side menu and then select your project under PROJECT section. Then select Build Settings and search for the Code Signing .

bullet Select the Provisioning Profile that you installed earlier for all values under this heading.

bullet Select Code Signing Identity as automatic for all values under this heading.

XcodeCodeSigning

bullet Select your project under TARGETS section.Then again select Build Settings and search for the Code Signing. Repeat the above process again to make sure all the values matches with new provisioning profile.

7.2 Registering the Device for Push:

Navigate to the AppDelegate.m class and change the application:didFinishLaunchingWithOptions: method to look like this:


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 

{

	// Intitializing App42API 

	[App42API initializeWithAPIKey:@"API_KEY" andSecretKey:@"SECRET_KEY"];



    // Let the device know we want to receive push notifications

    // Register for Push Notitications, if running on iOS 8

    if ([application respondsToSelector:@selector(registerUserNotificationSettings:)])

    {

        UIUserNotificationType userNotificationTypes = (UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound);

        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:userNotificationTypes categories:nil];

        [application registerUserNotificationSettings:settings];

        [application registerForRemoteNotifications];

    }

    else

    {

        // Register for Push Notifications, if running iOS version < 8

        [application registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound)];

    }



    return YES;

}

The above code tells the OS that this App wants to receive push notifications.

Now add this delegate method in the AppDelegate.m class that will be called in case of success and failure of the registration.


-(void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken

{

   // Prepare the Device Token for Registration (remove spaces and < >)

   NSString *devToken = [[[[deviceToken description]

		stringByReplacingOccurrencesOfString:@"<"withString:@""]

		stringByReplacingOccurrencesOfString:@">" withString:@""]

		stringByReplacingOccurrencesOfString: @" " withString: @""];



	NSLog(@"My token is: %@", devToken);

}

 

-(void)application:(UIApplication*)application didFailToRegisterForRemoteNotificationsWithError:(NSError*)error

{

    NSLog(@"Failed to get token, error: %@", error);

}

When your App registers for remote (push) notifications, it tries to obtain a device token. A device token is the address to which a push notification will be delivered.

7.3 Registering the device to App42 Push Server:

After getting the device token you need to register your device with the App42 Server to set up a connection to APNS to send the push notification to this device token. Change the delegate method application:didRegisterForRemoteNotificationsWithDeviceToken: in the AppDelegate.m class to look like this:


-(void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken

{

    // Prepare the Device Token for Registration (remove spaces and < >)

	NSString *devToken = [[[[deviceToken description]

		stringByReplacingOccurrencesOfString:@"<"withString:@""]

		stringByReplacingOccurrencesOfString:@">" withString:@""]

		stringByReplacingOccurrencesOfString: @" " withString: @""];

    

    NSLog(@"My token is: %@", devToken);

/** Register the device token for App42 Push notification services**/

    [self registerUserForPushNotificationToApp42Cloud:devToken];

}

-(void)registerUserForPushNotificationToApp42Cloud:(NSString*)deviceToken

{

    PushNotificationService *pushObj=[App42API buildPushService];

    @try

    {

        PushNotification *pushNotification=[pushObj registerDeviceToken:deviceToken 

															   withUser:@"User Name"];

        [pushNotification release];

    }

    @catch (App42Exception *exception)

    {

        NSLog(@"%@",exception.reason);

    }

    @finally

    {

        [pushObj release];

    }

}

7.4 Sending Push Notification:

The push notification can be sent from the iOS Application as well as from the AppHQ console.

  • 7.4.1 Sending Push from your iOS Application:

Now to send a push notification, call the following method in a commonly used class in your project so that you can call this whenever you want to:


-(void)sendPush:(NSString*)message toUser:(NSString*)userName

{

    @try

    {

        NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];

        [dictionary setObject:message forKey:@"alert"];

        [dictionary setObject:@"default" forKey:@"sound"];

        [dictionary setObject:[NSNumber numberWithInt:1] forKey:@"badge"];

        

        PushNotificationService *pushObj=[App42API buildPushService];

        PushNotification *push = [pushObj sendPushMessageToUser:userName withMessageDictionary:dictionary];



        [pushObj release];

    }

    @catch (App42Exception *exception)

    {

        NSLog(@"Reason = %@",exception.reason);

    }

    @finally

    {

        

    }

}

Note:- To increment badge automatically when message received, send “increment” as a value for key “badge” in the above message dictionary.

In the sample, we have written this method inside ViewController.m.

Above method implements App42 PushNotificationService API sendPushMessageToUser to send a Push message to a specific user. Likewise, App42 PushNotificationService has several APIs for sending push messages.

  • 7.4.2 Sending Push from AppHQ Console:

To send Push messages from AppHQ Console, Login to AppHQ Console and select Users under Push Notification in AppHQ Menu.

bullet Select your App42 App name from drop down menu under Users section.

bullet Select the user name to whom you want to send Push message.

bullet Click Send Push.

SendPushFromAppHQ

bullet Type your message in the Message section in the Send Push window and Click Send and you are done.

TypeMessage

bullet For the detail delivery reports you can see the Push Logs by selecting Push Logs option from the left-side menu and then the respective App42 App from the drop down under Push Logs.

PushLogs

bullet You can also send push messages to All your users by selecting Send Push To All instead of Send Push.

7.5 Handling Push Notifications When Received:

If you want to take any actions when you receive push notification then you need to add the following delegate method in the AppDelegate.m class:


- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo

{

       NSLog(@"%s..userInfo=%@",__FUNCTION__,userInfo);

 

      /**

       * Dump your code here according to your requirement after receiving push

       */

}

7.6 Sending Message from Server Side/other SDKs with Sound and Badge Effect

If you want to send push message with sound and badge effect on iOS device, you have to pass JSON string in below format using JAVA SDK. Similarly , you can use other server side SDK to achieve this.


PushnotificationService pushnotificationService = App42API.buildPushnotificationService();

String userName = "Nick";

//Message format for iOS device with sound and badge

String message = "{'alert':'Hi There...','badge':1,'sound':'default'}";

PushNotification pushNotification = pushNotificationService.sendPushMessageToUser(userName,message);

You can also do it from AppHQ by putting this JSON format in message text area for sending message to iOS device with sound and badge effect.

7.7 Sending Message to Channel

App42 Push notification also supports channel subscription model where user can subscribe on channel of his interest to receive the notification. You can send message to channel which will deliver message to all users who are subscribed to that channel.

A channel can be created from AppHQ console. Go to Push Notification -> Click on Channels -> Select your App -> Click on add channel button

Once channel is created you can ask user for subscription on the channel. Below is the code snippet for the same


-(void)subscribeChannel:(NSString*)channelName toUser:(NSString*)userName

{

    @try

    {

        PushNotificationService *pushObj=[App42API buildPushService];

        [pushObj subscribeToChannel:channelName userName:userName deviceToken:deviceToken deviceType:@"iOS"];

        [pushObj release];

    }

    @catch (App42Exception *exception)

    {

        NSLog(@"Reason = %@",exception.reason);

    }

    @finally

    {    

    }

}

-(void)sendPush:(NSString*)message toChannel:(NSString*)channelName

{

    @try

    {

        NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];

        [dictionary setObject:message forKey:@"alert"];

        [dictionary setObject:@"default" forKey:@"sound"];

        [dictionary setObject:@"2" forKey:@"badge"];

        

        PushNotificationService *pushObj=[App42API buildPushService];

        [pushObj sendPushMessageToChannel:channelName withMessageDictionary:dictionary];

        [pushObj release];

    }

    @catch (App42Exception *exception)

    {

        NSLog(@"Reason = %@",exception.reason);

    }

    @finally

    {    

    }

}

7.8 Scheduling Message to User

You can also schedule message to your app user on specified time from AppHQ console. To do this, go to Push Notification -> Click on Users -> Select your app -> select target users/device and click on schedule push button. Now type your message in pop up and pass your time to schedule the message.

7.9 Scheduling message to Channel

Message scheduling on channel can be done in similar way. Go to Push Notification -> Click on Channels -> Select your app -> select target channel and click on schedule push button. Now type your message in pop up and pass your time to schedule the message.

8. Doing Push Analytics

Push notification goes from App42 server to APNS and then device. Delivery of Push notification is not guaranteed from APNS to device and it is stated as best effort. Once it is delivered on user device, there might be a chance that user clears it without actually opening the message. Using App42 Push Analytics, you can track how many push notification was sent from your side, and how many were opened by the user. You can see these analytics from AppHQ console which will give a better insight of push notification campaign.

If you want to track push message read/opened event you have to simply put following snippet after Message is clicked and lands to your app. This will enable tracking of push message and analytics can be seen from AppHQ console.


    @try

    {

        LogService *logService = [App42API buildLogService];

        [logService setEventWithName:@"Opened" forModule:@"Message"];

        [logService release];

    }

    @catch (App42Exception *exception)

    {

        NSLog(@"Description=%@",exception.reason);

    }

9. Send Multilingual Push Notification

Once your device is registered for Push Notification you are ready to send multilingual(UTF-8) push message to your app user using following code snippet from any App42 SDK (Android/Java/WP etc)


NSString *message = @"Nick";

NSString *userName = @"Message which you have to send";

NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"true",@"dataEncoding", nil];

[pushNotificationService setOtherMetaHeaders:dict];

PushNotification *pushNotification = [pushNotificationService sendPushMessageToUser:userName message:message];

NSLog(@"Message=%@",pushNotification.message);

NSLog(@"UserName=%@",pushNotification.userName);

NSLog(@"Expiry=%@",pushNotification.expiry);

For more details of Push Notification Documentation