Follow

Set Up Push Notifications

Set Up Push Notifications

In iOS, push notifications use the Apple Push Notification Service (APNS). Kahuna acts as an intermediary on your behalf, managing APNS tokens for your users and sending your notifications to Apple for distribution to your users. See Before You Begin for information about push notifications with Kahuna.

To set up push notifications, you need to:

Generate a Certificate Signing Request (CSR)

Generate your (CSR) to be able to create a Push SSL Certificate for your app.

Note: If you already have a CSR for your app, skip this procedure.

  1. From the Utilities folder in Applications on your Mac, open the Keychain Access application.

  2. From the Keychain Access menu (in the Apple toolbar in the top left of your screen), select Certificate Assistant, then select Request a Certificate from a Certificate Authority. The Certificate Assistant opens.
  3. In the User Email Address field, provide your email address.
  4. In the Common Name field, provide a name for your application (for example, MyCoolApp).
  5. Check the Saved to disk option, then click Continue to save your CSR.

Enable Push Notifications

Note: If your app already supports push, skip this procedure.

  1. Ensure your application is properly provisioned in the iOS Provisioning Portal.

    Note: Push does not support the wildcard App ID. Your application must have a valid Bundle Identifier (including Development builds).

  2. The App IDs area of the iOS Provisioning Portal provides a description for your application as well as little green or gray indicators for Push Notification; both Development and Distribution. Click Edit to continue. The Push Notifications dialog opens.

    Note: To configure your app, you need to be the Team Agent.

  3. Enable the Apple Push Notification service for Development and Distribution. Kahuna recommends you enable the Apple Push Notification service for both so that you can test before deploying to production.
  4. Click on the Create Certificate button and point to the CSR you created above.
  5. Follow the steps to specify your CSR.
  6. After you have generated your Push SSL Certificate, you are directed back to the Enable Push Notification dialog where the status indicator is green and Enabled.
  7. Click Download to download your Push SSL Certificate.
  8. Open the downloaded certificate. The Keychain Access application opens.
  9. Under My Certificates, select the certificate that was just added, then select Export Items from the File menu.
  10. In the Save dialog, provide a name for the certificate and click Save.

    Note: Make sure you save the certificate file in Personal Information Exchange (.p12) format.

Upload the Push Certificate to Kahuna

  1. In the Kahuna application, click on the top bar, then click Settings to open the Settings page.
  2. Scroll down to the Push Authorization section.
  3. In the Apple Push Certificates area, drag and drop the certificate you downloaded from the iOS Provisioning Portal.

Support Push in Your Application

To support push notifications in your application, incorporate the following lines into your application delegate.

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // Call other Kahuna integration APIs here, such as launchWithKey, loginWithCredentials
    [Kahuna enablePushNotifications];

    // If you are implementing didReceiveRemoteNotification:fetchCompletionHandler, call 
    // [Kahuna handleNotification] in that method
    // Otherwise, call handleNotification as shown below
    [Kahuna handleNotification:[launchOptions valueForKey:UIApplicationLaunchOptionsRemoteNotificationKey]
                                    withApplicationState:application.applicationState];

    // Add your app initialization code here
    return YES;
}

- (void) application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings 
                                   *)notificationSettings
{
    [[UIApplication sharedApplication] registerForRemoteNotifications];
}

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    [Kahuna setDeviceToken:deviceToken];
}

-(void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{
    [Kahuna handleNotificationRegistrationFailure:error];
}

Regular Push Notifications

If you use standard push notifications, add this method to your application delegate:

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    [Kahuna handleNotification:userInfo withApplicationState:application.applicationState];
}

Actionable Push Notifications

If you use iOS Push Categories in your app, add this method to your application delegate:

- (void)application:(UIApplication *)application handleActionWithIdentifier:(NSString *)actionIdentifier
                                                      forRemoteNotification:(NSDictionary *)userInfo
                                                          completionHandler:(void (^)())completionHandler
{
    [Kahuna handleNotification:userInfo withActionIdentifier:actionIdentifier
                                        withApplicationState:application.applicationState];

    // Call the completion handler here
}

iOS 10

If you have updated your app to use the new iOS 10 UserNotification framework and are using a UNUserNotificationCenter delegate to handle app notifications, Kahuna recommends that you initialize the Kahuna SDK before you set your NotificationCenter delegate. If your application architecture does not allow for this, but you want the Kahuna SDK to track push notifications, call the following methods after you set your UNUserNotificationCenter delegate.

[Kahuna setUserNotificationCenterDelegate:<YOUR_NOTIFICATION_CENTER_DELEGATE>];

Rich Content in Push Notifications

If you want to use rich content in push notifications, you need to implement a Notification Service Extension in your iOS app.

  1. In Xcode, select File > New > Target.
  2. In the popup, select Notification Service Extension to add a Notification Service Extension target to your project.

    An example Notification Service Extension is shown below.

    // NotificationService.m
    // KahunaNotificationExtension
    #import "NotificationService.h"
    @interface NotificationService ()
    @property (nonatomic, strong) void (^contentHandler)(UNNotificationContent *contentToDeliver);
    @property (nonatomic, strong) UNMutableNotificationContent *bestAttemptContent;
    @end
    @implementation NotificationService
    - (void)didReceiveNotificationRequest:(UNNotificationRequest *)request withContentHandler:(void 
                            (^)(UNNotificationContent * _Nonnull))contentHandler {
        self.contentHandler = contentHandler;
        self.bestAttemptContent = [request.content mutableCopy];
        // Modify the notification content here
        if ([request.content.userInfo objectForKey:@"media_attachment"]) {
            NSURL *url = [NSURL URLWithString:[request.content.userInfo objectForKey:@"media_attachment"]];
            [[[NSURLSession sharedSession]
              downloadTaskWithURL:url
              completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * 
                               _Nullable error) {
                      if (!error) {
                          NSFileManager *fileManager = [NSFileManager defaultManager];
                          NSError *error;
                          
                          // Getting application's document directory path
                          NSArray * tempArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, 
                                NSUserDomainMask, YES);
                          NSString *docsDir = [tempArray objectAtIndex:0];
                          
                          // Adding a new folder to the documents directory path
                          NSString *appDir = [docsDir stringByAppendingPathComponent:@"/Reader/"];
                          
                          // Checking for directory existence and creating if not already exists
                          if(![fileManager fileExistsAtPath:appDir])
                          {
                              [fileManager createDirectoryAtPath:appDir withIntermediateDirectories:NO 
                                   attributes:nil error:&error];
                          }
                          
                          // Retrieving the filename from the response and appending it again to the path
                          // This path "appDir" will be used as the target path
                          appDir =  [appDir stringByAppendingFormat:@"/%@",[response suggestedFilename]];
                          
                          // Moving the file from temp location to app's own directory
                          BOOL fileCopied = [fileManager moveItemAtPath:[location path] toPath:appDir error:&error];
                          
                          NSURL *copiedFileUrl = [NSURL fileURLWithPath:appDir];
                          NSError *attachError;
                          UNNotificationAttachment *attachment = [UNNotificationAttachment
                                                                  attachmentWithIdentifier:@"media_attachment"
                                                                  URL:copiedFileUrl
                                                                  options:nil
                                                                  error:&attachError
                                                                  ];
                          if (!attachError) {
                              self.bestAttemptContent.attachments = @[attachment];
                              self.contentHandler(self.bestAttemptContent);
                          } else {
                              self.contentHandler(self.bestAttemptContent);
                          }
                      } else {
                          self.contentHandler(self.bestAttemptContent);
                      }
                  }]
             resume];
            
        } else {
            self.contentHandler(self.bestAttemptContent);
        }
    }
    - (void)serviceExtensionTimeWillExpire {
        // Called just before the extension will be terminated by the system
        // Use this as an opportunity to deliver your "best attempt" at modified content, 
        // otherwise the original push payload will be used
        self.contentHandler(self.bestAttemptContent);
    } 

If you do not want to use the code provided above, use the media_attachment field in the push message payload in your Notification Service Extension implementation. You can access the media_attachment resource URL in the userInfo dictionary of the notification using the "media_attachment" key. For example:

NSString *resourceUrlString = [request.content.userInfo objectForKey:@"media_attachment"];

Optional - Set Up a Delegate

The Kahuna SDK can notify you if your application receives a Push notification sent from Kahuna.

To set up a delegate

  1. Implement the Protocol in your AppDelegate file, as shown below.

    #import <Kahuna/Kahuna.h>
    @interface AppDelegate : UIResponder <UIApplicationDelegate, KahunaDelegate>
  2. In your AppDelegate, implement the Kahuna Push protocol and assign the delegate to your own class to be called.

    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
    {
        // Set AppDelegate as the delegate for Kahuna Push Notifications
        [Kahuna sharedInstance].delegate = self;
    
        // Call other Kahuna integration APIs her, for example: launchWithKey, loginWithCredentials and so on
    
        // Add your app initialization code here
        return YES;
    }
  3. With Kahuna you can pass in extra parameters to your own application and receive them from the Notification Delegate as shown below.

    Note: Decide which custom parameters (if any) your app will support and add any error handling logic in case a push you receive does not contain any extra parameters.

    - (void)kahunaPushMessageReceived:(NSString *)message withDictionary:(NSDictionary *)extras
                                                    withApplicationState:(UIApplicationState)applicationState
    {
        NSLog(@"Received Push from Kahuna!");
        // Check on the applicationState before deep linking into the app
        // Push received when app is in Foreground should not take users to specific view via DeepLinking
        // Non view navigation code can still be performed when Push is received with app in foreground
        NSString *value = [extras valueForKey:@"DEEP_LINKING_PARAM_KEY"];
        if (value) {
            if (applicationState != UIApplicationStateActive) {
                // Create deep links into the app
            } else {
                // Push came when the app is in foreground. You can show an UIAlertView dialog with the message.
                // When the user clicks on the "OK" button,  into the app
            }
        }
        // For iOS8 actionable push notifications, we send the selected action in this callback
        // Actionable push notifications do not need the applicationState check as the user cannot
        // take an action when the app in the foreground
        if ([extras valueForKey:@"k_action_identifier"] != nil) {
            NSString *pushAction = [extras valueForKey:@"k_action_identifier"];
            // Act on the pushAction to perform actions for the user
        }
    }

Optional - Set your Application Badge Number

Kahuna can receive requests from your server to do badge pushes.

The Kahuna SDK provides methods for setting and getting your application's badge number. Below are examples of how you can utilize these methods in your app.

If you have already implemented your own badge, this procedure is not necessary.

Note: Set and get the badge number wherever you think is appropriate; the examples below illustrate how to perform the correct method calls.

  1. Set the badge number.

    [Kahuna sharedInstance].badgeNumber = 2;
  2. Obtain the badge number.

    NSInteger badgeValue = [Kahuna sharedInstance].badgeNumber;

After you complete these steps, your team has a robust push notification delivery system capable of targeting key groups of users. Now, follow the steps in Set Up In-App Messaging.

Was this article helpful?
0 out of 0 found this helpful
Have more questions? Submit a request

Comments