Rich Push Widget

iOS Push Notifications

This easy and elaborated tutorial will enable you to configure your iOS app to send and receive push notifications. App42 Cloud API provides push notifications using APNS (Apple Push Notification Services). The best part about using App42 Push for your iOS app is that you can schedule and target people with geo based push notifications as well. Along with these features, you can also track the response rate of your notifications using the detailed analytics. Let’s begin with configuring your iOS project and then the quick process to start sending push:

Configure your iOS Project

Here are the prerequisites to configure Push Notifications for iOS applications :

bullet An iOS Developer Program membership on iOS Dev Center

bullet An iPhone/iPad

bullet A Server - this is where App42 Push Service plays a vital role

Once you have all of these, you would need to generate AppID and SSL certificate on Apple 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 application for push notification.

1. Generating Certificate Signing Request

Certificate Signing Request (CSR) file would be required from your development machine to manually generate the certificate, which will allow you to authenticate the creation of SSL certificate.

Follow these simple steps to complete this process:

bullet Launch the Keychain Access

bullet Select Certificate Assistant -> Request a Certificate From a Certificate Authority… and ensure that no private key is selected in the main Keychain Access window

RequestCSR

bullet Enter your Email Address, Common Name, check Saved to disk and click on Continue to save it on your hard drive

CertficateAssistant

2. Creating App ID

All the iOS applications installed on your development device need an App ID. If you’ve already created an App ID, you may use it without any wildcard characters. To create a new one, follow these simple steps:

bullet Open iOS Dev Center, login and select Certificates, Identifiers & Profiles

bullet Select App IDs under Identifiers from the iOS Apps section:

bullet Click on + button as shown below:

AppIds

bullet Enter a name for your App ID under App ID Description

bullet Select your preferred App ID prefix

bullet Choose Explicit App ID in App ID Suffix and enter the Bundle ID as shown below:

AppIDDescription

bullet Make sure to check Push Notifications for this App ID under App Services

bullet Select Continue and Confirm if all the details you entered previously are correct and select Submit button to finish the creation of your App ID

AppServices

3. Creating SSL Certificate

Now the next step is to generate SSL certificate to make a secure connection between 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 the list of App IDs and select the App ID that you just created:

AppIDSelection

bullet Select Edit button in the presented screen

EditAppID

bullet Scroll down to Push Notifications to create the SSL certificate

bullet Choose Development SSL Certificate to create a new SSL certificate as we are creating for the development environment

CreateCertificate

bullet You will be navigated to Add iOS Certificate screen where you will see information on creating Certificate Signing Request(CSR) that we have created already under Section-1. Simply select Continue

AddiOSCertificate

bullet Upload the CSR file in the next step by browsing to .certSigningRequest file and generate the SSL certificate

UploadCSR

bullet It might take a few seconds to generate the certificate, when it is ready, it is recommended that the certificate is downloaded and saved in a single folder where all the generated files are stored

DownloadCertificate

Congratulations! You have created a valid certificate for sending push notifications in the development environment, you may repeat the same process for Production.

4. Creating .p12 file:

bullet To install the newly created SSL certificate file to your Keychain Access, go ahead and double click on the downloaded certificate file.

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

ExportCertificate

bullet Enter the filename and select the location and click Save

bullet Provide the export password when asked, you may also be asked to provide system account password to allow Keychain Access to export

bullet Make your .p12 file compatible with the App42 server by following these steps:

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

b. Open the terminal and go to the folder having both these 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

Select Provisioning Profile option from the sidebar under Certificates, Identifiers & Profiles on iOS Dev Center and select + button as shown below

ProvisionalProfile

Now, follow the 4-step Add iOS Provisioning Profile wizard to create the provisioning profile

Step-1 : Select Type

Select iOS App Development under Development and then click Continue

ProfileTypeSelection

Step-2 : Configure

Select the App ID created section-2 of this tutorial and click on Continue

ProvisionAppID

Step-2.1 Select Certificates :

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

SelectCertificate

Step-2.2 Select Devices :

Select the devices you wish to include in this provisioning profile and click on 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 on Generate

GenerateProfile

Step-4 : Download

Select Download to get the generated profile. Add the profile to Xcode by double clicking on it and that is it

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 Notifications

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

bullet Sign up with App42 platform to get started and create your first app

bullet If you are already registered, login to AppHQ console, select your desired app and click on Unified Notification in AppHQ left side Menu

bullet Select iOS in Settings as shown below:

iOSPushSettingsLayOUT

bullet Click on Upload File(.p12) button to browse your iphone_dev.p12 file and upload it

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

bullet Select the environment from the drop down menu

bullet Click on the submit button

UploadP12

Repeat the same process to configure App42 Cloud API App for Push when it is ready for distribution, the exception would be selecting Production environment during the process.

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.

bullet We have encapsulated the entire code written below in a sample project. Download the sample here 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 must have received after completing the integration steps while getting started in AppHQ Console

Xcode settings to enable iOS Application for Push Notifications:

bullet In order to configure your app for Push Notifications, you will need to modify Bundle Identifier and Code Signing as per the Provisional Profile you 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

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 matche with new provisioning profile

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 particular app wants to receive push notifications.

Now add the following delegate method in the AppDelegate.m class, which will be called in case of successful and failed 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 the remote (push) notifications, it tries to obtain a device token. A device token is the address which a push notification will be delivered to.

Registering the device with App42 Push Server:

After getting the device token you would have to register your device with the App42 Server to set up a connection with APNS to send push notification to this particular device token. Change the delegate method application:didRegisterForRemoteNotificationsWithDeviceToken: in the AppDelegate.m class and it should 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];
    }
}

Sending Push Notifications:

The push notifications can be sent from the iOS app as well as from the AppHQ console.

Sending Push from your iOS App:

Call the following method in a commonly used class in your project so that you can call the any time you prefer 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 whenever the message is received, send “increment” as a value for key “badge” in the above message dictionary.

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

The above method implements App42 PushNotificationService API sendPushMessageToUser to send a Push notification to a specific user. Simplarly, App42 PushNotificationService has several APIs that enable you to send as many push notifications as you want.

Sending Push from the AppHQ Console:

To send Push notifications from AppHQ Console, simply login and select Users under Unified Notifications > Push in AppHQ left side Menu

bullet Select your app from Users section

bullet Select the user name you want to send your notification to

bullet Click Send Push and the notification will be sent

bullet Type your message in the Send Push window and you would be able to send the notification

TypeMessage

bullet For the detailed delivery reports you may check the Push Logs by selecting Unified Push Notifications > Push > Logs from AppHQ left side menu:

bullet Select your app from the drop down under Logs:

PushLogs

bullet You can also send push notifications to your entire user list by selecting Send Push To All instead of Send Push

Handling Push Notifications After Receiving:

If you want to take any action after you receive the push notification then you would need to add the following 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
       */
}

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

In case you want to send push notifications with sound and badge effects on iOS devices, you would have to pass JSON string in the following format using JAVA SDK. Similarly, you can use other server side SDKs as well 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 may also achieve this through AppHQ by putting this JSON format in the message text area for sending messages to iOS devices with sound and badge effects.

Sending Message to a Channel

App42 Push also supports the channel subscription model where user can subscribe to a channel of their interest to receive the notifications of that particular channel. You can send messages to that channel so that all the users who are subscribed to that channel will get that notification. A channel can be created in the AppHQ console. Simply follow these steps:

bullet Click on Unified Notification

bullet Click on Push -> Click on Channels

bullet Select your app -> Click on Add channel button

AddChannelFromConsole

Once channel is created you may ask users to subscribe to that channel. Please use the following code snipped to do this:

-(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
    {    
    }
}

Scheduling Message to a User

You can also schedule messages for your app users so that they receive it in future on a specified time. Here are the steps for the same:

bullet Click on Unified Notification

bullet Click on Push -> Click on Users

bullet Select your app -> Delect target user and click on manage

bullet Click on Send button and type your message in the pop up and enter your desired time to schedule the message

SchedulePushMessageFromConsole

Scheduling message to a Channel

Message scheduling for any channel can be done in similar way. Follow these simple steps:

bullet Click on Unified Notification

bullet Click on Push -> Click on Channels

bullet Select your app -> Select target channel and click on manage

bullet Click on Send Push button and type your message in the pop up and enter your desired time to schedule the message

7. Doing Push Analytics

Push notification is initially shot from the App42 server to APNS, and then is sent to the devices. There is no guarantee that your push will get delivered, hence it is stated as a 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);
    }

8. Send Multilingual Push Notifications

By registering your application with App42 you are automatically empowered to send multilingual(UTF-8) push messages to your app user using the following code snippet from any of the App42 SDKs

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 and advanced features, please check out the Push Notification Documentation.