Push Notification is undoubtedly the king of all mobile engagement campaigns. It might be a bit tricky to implement in iOS apps. To help all the iOS Devs out there, we have come up with a tutorial that will help you get done with the hassle free integration of push notifications. This tutorial covers some of the difficult steps such as configuring your own service and creating p12 files among other necessary tasks.

Taking the recent queries into the account on configuring push notifications in iOS apps using App42 Backend API, we have decided to put together the steps for iOS developers for quick help and ready reference.





Steps involved in configuring the push notification service for iOS(all versions):

1. Firstly, get a certificate from iOS Dev Center, here is a step by step guide on how you can do that: App42 iOS Push Notification Tutorial

2. Double click the .cer file, which was downloaded in the above step, to install it.

3. Convert the iPhone developer certificate into a .p12 file by following the below mentioned steps:

Open the Keychain Access application (in the Applications/Utilities folder)

Select the Keys category in Keychain Access

Select the private key associated with your iPhone Development Certificate. The private key is identified by the iPhone Developer as: public certificate that is paired with it.

Select File > Export Items

Save your key in the Personal Information Exchange (.p12) file format

You will be prompted to create a password which will be used when you will attempt to import this key on another computer.

4. Make your .p12 file compatible with App42 server by following the below mentioned steps:

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

Open terminal and go to the folder that has both the files

[code java]shephertz-technologiess-iMac:~ shephertztechnologies$ cd "your folder path"[/code]

Now execute the following commands in the terminal:

[code java]openssl x509 -in developer_identity.cer -inform DER -out developer_identity.pem -outform PEM openssl pkcs12 -nocerts -in yourPrivateKey.p12 -out yourPrivateKey.pem openssl pkcs12 -export -inkey yourPrivateKey.pem -in developer_identity.pem -out iphone_dev.p12[/code]

Where,

– developer_identity.cer <= certificate you downloaded from Apple

– yourPrivateKey.p12 <= your private key

5. Upload iphone_dev.p12 file to the AppHQ console

Login to AppHQ console and select your App Name in the drop down

Select iOS settings in Settings

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

Enter password given during creation of the iphone_developer.p12 file

Select the environment from the drop down menu

Click on the submit button and it’s done here

6. Add Push Notification Entitlements

Go to your project target’s Capabilities tab and add Push Notifications Entitlements.

7. Open your Xcode project and navigate to the AppDelegate.m class and change the application:didFinishLaunchingWithOptions: method to look like this:

[code java]//Define constant for version check : #define SYSTEM_VERSION_GRATERTHAN_OR_EQUALTO(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending) -(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{ [self registerForRemoteNotifications]; return YES; } - (void)registerForRemoteNotifications { if(SYSTEM_VERSION_GRATERTHAN_OR_EQUALTO(@"10.0")){ UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter]; center.delegate = self; [center requestAuthorizationWithOptions:(UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionBadge) completionHandler:^(BOOL granted, NSError * _Nullable error){ if(!error){ [[UIApplication sharedApplication] registerForRemoteNotifications]; } }]; } else { // Code for old versions if ([application respondsToSelector:@selector(registerUserNotificationSettings:)]) { // Register for Push Notitications, if running on iOS 8 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)]; } } }[/code]

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

8. Now you need to add the following delegate methods in your AppDelegate.m in order to receive push notification:

[code java]-(void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken{ NSString *token = @""; token = [[NSString alloc] initWithString:[[[[deviceToken description] stringByReplacingOccurrencesOfString:@"" withString:@""] stringByReplacingOccurrencesOfString:@" " withString: @""]]; NSLog(@"Device Token: %@", token); } -(void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error{ NSLog(@"failed to get device token error:%@",error.localizedDescription); }[/code]

When your App registers for remote (push) notifications, it tries to obtain a “device token”. This is a 32-byte number that uniquely identifies your device. A device token is the address to which a push notification will be delivered.

9. 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:

[code java]-(void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken{ NSString *token = @""; token = [[NSString alloc] initWithString:[[[[deviceToken description] stringByReplacingOccurrencesOfString:@"" withString:@""] stringByReplacingOccurrencesOfString:@" " withString: @""]]; NSLog(@"Device Token: %@", token); [self registerUserForPushNotificationToApp42Cloud:token]; } -(void)registerUserForPushNotificationToApp42Cloud:(NSString*)deviceToken { PushNotificationService *pushService = [[App42API buildPushService] retain]; [pushService registerDeviceToken:deviceToken withUser:[App42API getLoggedInUser] completionBlock: ^(BOOL success, id responseObj, App42Exception *exception) { if (success) { PushNotification *pushNotification = (PushNotification*)responseObj; NSLog(@"UserName=%@",pushNotification.userName); NSLog(@"isResponseSuccess=%d",pushNotification.isResponseSuccess); NSLog(@"Response=%@",pushNotification.strResponse); } else { NSLog(@"Exception = %@",[exception reason]); NSLog(@"HTTP Error Code = %d",[exception httpErrorCode]); NSLog(@"App Error Code = %d",[exception appErrorCode]); NSLog(@"User Info = %@",[exception userInfo]); } }]; [pushService release]; }[/code]

10. 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:

[code java]-(void)sendPush:(NSString*)message { 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]; [pushObj sendPushMessageToUser:@"User Name" withMessageDictionary:dictionary completionBlock: ^(BOOL success, id responseObj, App42Exception *exception) { if (success) { PushNotification *push = (PushNotification*)responseObj; } else { NSLog(@"Reason = %@",exception.reason); } [pushObj release]; }]; }[/code]

The pushDictionary in the above code should always follow the same structure as mentioned above to deliver the push notification successfully using App42 Server. You can remove or add the items to the pushDictionary if needed as per the Apple guidelines.

11. 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:

[code java]- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo { NSLog(@"%s..userInfo=%@",__FUNCTION__,userInfo); /** * Dump your code here according to your requirement after receiving push */ } //From iOS10, We can display notification when application is in foreground. //Called when a notification is delivered to a foreground app. -(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler: (void (^)(UNNotificationPresentationOptions options))completionHandler{ NSLog(@"User Info : %@",notification.request.content.userInfo); completionHandler(UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionBadge); } //Called to let your app know which action was selected by the user for a given notification. -(void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse: (UNNotificationResponse *)response withCompletionHandler:(void(^)())completionHandler{ NSLog(@"User Info : %@",response.notification.request.content.userInfo); completionHandler(); }[/code]

With the above mentioned step, your App has been successfully set up to receive/send push notifications through our App42 Server using App42 Push Notification Service.

It would be great to hear the views from the readers of this blog. In case you have any more questions, please feel free to reach out to us at support@shephertz.com.

Para incrementar el compromiso del usuario, las notificaciones son ampliamente usadas en aplicaciones móviles nativas. Aunque parece una característica muy útil es un poco complicado implementarla. Configurando su propio servidor, creando archivos p12 son algunos de los pasos que hacen las cosas un poco más complicadas para los desarrolladores.



También hemos recibido algunas inquietudes en los últimos días acerca de configurar el servicio de notificaciones en un dispositivo iOS usando App42. Entonces, decidimos dejar aquí los pasos para desarrolladores su beneficio y referencia rápida.





Pasos involucrados en configurar el servicio de notificaciones:

1. Primero debe crear una certificación desde iOS Dev Center, aqui puede encontrar un tutorial paso a paso para hacer esto:App42 iOS Push Notification Tutorial

2. Doble click el archivo .cer, el cual fue descargado en el paso anterior, instálelo.

3. Convierta el certificado del desarrollador de iPhone a un archivo .p12 siguiendo los pasos que se mencionan abajo:

Abra la aplicación Keychain Access (en Aplicaciones/Carpeta de utilidades)

Seleccione la categoría Keys en Keychain Access.

Seleccione la clave privada asociada con su iPhone Development Certificate. La clave privada es identificada por el desarrollador de iPhone como: certificado público con quien es conectado.

Seleccione Archivo, > Export Items

Guarde su clave en Intercambio de Información Personal (Personal information Exchange) (.p12) archivo de formato.

Se le pedirá que cree una contraseña la cual será usado cuando este intente importar esta clave a otro computador.

4. Haga compatible su archivo .p12 con el servidor APP42 siguiendo los pasos abajo mencionadosÑ

Mantenga los archivos .cer y .p12 en una sola carpeta.

Abra una terminal y vaya a la carpeta que contiene los dos archivos.

shephertz-technologiess-iMac:~ shephertztechnologies$ cd "your folder path"

Ahora ejecute los siguientes comandos en la terminal

openssl x509 -in developer_identity.cer -inform DER -out developer_identity.pem -outform PEM openssl pkcs12 -nocerts -in yourPrivateKey.p12 -out yourPrivateKey.pem openssl pkcs12 -export -inkey yourPrivateKey.pem -in developer_identity.pem -out iphone_dev.p12

Donde:

- developer_identity.cer <= certificado que descargó desde Apple - yourPrivateKey.p12 <= su clave privada 5. Cargue el archivo iphone_dev.p12 a AppHQ console

Ingrese a la consola AppHQ y seleccione Push Notification en el menú AppHQ

Seleccione configuraciones iOS en Settings.

Seleccione App Name desde menú de abajo.

Busque su archivo iphone_developer.p12 dandole click en la opción “choose file” para cargar el archivo.

Ingrese la contraseña que se le dio durante la creación del archivo iphone_developer.p12

Seleccione el entorno desde el menú de abajo.

Dele click en el botón Submit y eso es todo.

6. Abra el proyecto Xcode y navegue hasta AppDelegate.m class y cambie la aplicación didFinishLaunchingWithOptions: parecido a este:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { // 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; }

El código de arriba le indica a OS que esta aplicación quiere recibir notificaciones

7. Ahora necesita agregar los siguientes métodos delegados en su AppDelegate.m con el fin de recibir notificaciones:

- (void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken { NSLog(@"My token is: %@", deviceToken); // Prepare the Device Token for Registration (remove spaces and ) NSString *devToken = [[[[deviceToken description] stringByReplacingOccurrencesOfString:@"" withString:@""] stringByReplacingOccurrencesOfString: @" " withString: @""]; NSLog(@"My Device token is: %@", devToken); } - (void)application:(UIApplication*)application didFailToRegisterForRemoteNotificationsWithError:(NSError*)error { NSLog(@"Failed to get token, error: %@", error); }

Cuando su aplicación se registre para notificaciones, intentará obtener un “device token”. Este es un número de 32-bytes que de manera única identifica su dispositivo. Un “device token” es la dirección a la cual las serán mandadas las notificaciones.

8. Después de obtener el “device token” necesita registrar su dispositivo con el servidor App42 para configurar la conexión a APNS para enviar las notificaciones a este “device token”. Cambie la aplicación del método delegado: didRegisterForRemoteNotificationsWithDeviceToken: en AppDelegate.m class para que se vea de esta manera:

- (void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken { NSLog(@"My token is: %@", deviceToken); // Prepare the Device Token for Registration (remove spaces and ) NSString *devToken = [[[[deviceToken description] stringByReplacingOccurrencesOfString:@"" withString:@""] stringByReplacingOccurrencesOfString: @" " withString: @""]; NSLog(@"My Device token is: %@", devToken); /** * Register the device token for App42 Push notification services */ [self registerUserForPushNotificationToApp42Cloud:devToken]; } -(void)registerUserForPushNotificationToApp42Cloud:(NSString*)deviceToken { ServiceAPI *serviceObj = [[ServiceAPI alloc]init]; serviceObj.apiKey = APP42_APP_KEY; serviceObj.secretKey = APP42_SECRET_KEY; PushNotificationService *pushObj = [serviceObj buildPushService]; @try { PushNotification *pushNotification =[pushObj registerDeviceToken:deviceToken withUser:@"User Name"]; [pushNotification release]; } @catch (App42Exception *exception) { NSLog(@"%@",exception.reason); } @finally { [serviceObj release]; [pushObj release]; } }

9. Ahora para enviar notificaciones, llame el siguiente método de una manera que use comúnmente en su proyecto, así que puede llamarlo cuando sea necesario.

-(void)sendPush:(NSString*)message { ServiceAPI *serviceObj = [[ServiceAPI alloc]init]; serviceObj.apiKey = APP42_APP_KEY; serviceObj.secretKey = APP42_SECRET_KEY; PushNotificationService *pushObj = [serviceObj buildPushService]; @try { NSMutableDictionary *pushDictionary = [NSMutableDictionary dictionary]; [pushDictionary setObject:message forKey:@"alert"]; [pushDictionary setObject:@"default" forKey:@"sound"]; [pushDictionary setObject:@"1" forKey:@"badge"]; PushNotification *pushNotification = [pushObj sendPushMessageToUser:@"User Name" withMessageDictionary: pushDictionary]; [pushNotification release]; } @catch (App42Exception *exception) { NSLog(@"%@",exception.reason); } @finally { [serviceObj release]; [pushObj release]; } }

PushDictionary en el código de arriba debe ser usado siempre siguiendo la misma estructura mencionada para enviar la notificación de manera exitosa usando el servidor App42. Puede remover y agregar elementos a pushDictionary si es necesario, de acuerdo a las pautas de Apple.

10. Si quiere realizar alguna acción cuando reciba notificaciones, entonces necesita agregar los siguientes métodos delegados en 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 */ }

Con el método mencionado arriba, su aplicación ha sido configurada de manera exitosa para recibir/enviar notificaciones a través de nuestro servidor App42 usando App42 Push Notification Service.

Seria grandioso escuchar de los lectores del blog. En caso que tenga más dudas por favor contáctenos a support@shephertz.com