Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Interactive Push Notifications on iOS Using App42 Cloud

DZone's Guide to

Interactive Push Notifications on iOS Using App42 Cloud

Learn how to enable interactive push notifications, one of the newest features for mobile apps revealed for iOS by Apple.

· Mobile Zone
Free Resource

Download this comprehensive Mobile Testing Reference Guide to help prioritize which mobile devices and OSs to test against, brought to you in partnership with Sauce Labs.

Apple has introduced an exciting API for iOS which facilitates one of the most awaited features for apps: interactive push notifications. This enables your users to have access to some additional functionality even if they are outside your application. With this feature, your users can type a reply, confirm a contact request, delete the message, and more without switching apps.

We receive a lot of queries on our support desk as to how App42 and this new feature can be bundled together to implement interactive push notifications.

We have made a sample project and will walk you through the code step-by-step. Before getting into the implementation details, we must know some classes which are going to be used frequently.

We have made a sample project and will walk you through the code step-by-step. Before getting into the implementation details, we must know some classes which are going to be used frequently.

Actions: An instance of UIUserNotificationAction represents a custom action that your app users can perform in response to a remote or a local notification. When a notification is delivered, it will be presented as a button, and clicking on the button will launch your app (either in the foreground or background), giving you a chance to perform the indicated action.

Categories: An instance of UIUserNotificationCategory encapsulates information about custom actions that your app users can perform in response to a local or push notification. Every notification can be set to a specific category.

Settings: An instance of UIUserNotificationSettings encapsulates the types of notifications that can be displayed to the user by your app.

Implementation Diagram:

Image title

Getting Started

Implementation of interactive push notifications is almost the same as that of standard push notifications, except that the in the former case the device needs to be registered for push notifications and push payload needs to be created. This blog will only focus on registering the device for push notifications, creating push payload, and handling the actions performed.
This blog assumes you have previous knowledge of configuring and sending push notifications using App42. If you are a new user, please go through this tutorial first.

To get started, first download the sample source code, unzip it, and open it in Xcode. Now open AppDelegate.m class from the project navigator in Xcode and search for the method createCategory. Let’s see how an action can be created:

Let’s walk through the above code step-by-step:

Identifier: The string that will be used later to identify the action chosen by the app user.

Title: The localized string that will be used as the button title for the action in the notification banner/alert.

ActivationMode: The mode (Background/Foreground) in which to run the app when the action is performed.

AuthenticationRequired: A Boolean value indicating whether the user must unlock the device before the action is performed. This is used only when activation mode is set to Background, and ignored otherwise.

Destructive: A Boolean value indicating whether the action is destructive. Use this property to signal to the user whether the action causes destructive behavior to the user’s data or the app. When the value of this property is YES, the system displays the corresponding button differently to indicate that the action is destructive.

In the same way, we can create other different actions. Now created actions can be encapsulated in a category, as follows:

//Creating Category
UIMutableUserNotificationCategory *interactiveCategory =    [[UIMutableUserNotificationCategory alloc] init];
interactiveCategory.identifier = INTERACTIVE_CATEGORY;
//Setting actions to the category 
[interactiveCategory setActions:@[action1,action2,action3] for Context:UIUserNotificationActionContextDefault];
[interactiveCategory setActions:@[action1,action2] forContext:UIUserNotificationActionContextMinimal];

Let’s walk through above code step-by-step:

Identifier: The name of the action group, i.e. the category which is needed to identify the category when any action is performed.

Default Context: The default context is for displaying the alert. In this context, the full UI is displayed for the notification’s alert. A maximum of four custom actions can be specified in this context.

Minimal Context: The context is for displaying notifications where space is minimal, such as notification banners, lock screen notification view, etc. In this context, a minimal UI is displayed for the notification’s alert. A maximum of two custom actions can be specified in this context.

Next, we can register for user notification settings by defining Notification type and settings as follows:

//Notification types
UIUserNotificationType notificationType = UIUserNotificationTypeAlert|UIUserNotificationTypeBadge|UIUserNotificationTypeSound;

//Notification Settings
UIUserNotificationSettings *notificationSettings = [UIUserNotificationSettings settingsForTypes:notificationType categories:[NSSet setWithObject:[self createCategory]]];

//Register settings
[application registerUserNotificationSettings:notificationSettings];

First, we defined the way the app will alert the user then we created notification settings using the notification type and the category returned by the createCategory method. Lastly, we registered the configured settings for the application.

Sending Push Notifications: Sending interactive push notifications is similar to the standard push notification with the addition of an extra key-value pair in the payload.

IN the sample open ViewController.m class and go to sendPush method.
NSMutableDictionary *pushMessageDict = [NSMutableDictionary dictionary];
[pushMessageDict setObject:@"Hello Buddy !" forKey:@"alert"];
[pushMessageDict setObject:@"default" forKey:@"sound"];
[pushMessageDict setObject:@"increment" forKey:@"badge"];
[pushMessageDict setObject:INTERACTIVE_CATEGORY forKey:@"category"];

You can see the extra key highlighted in the above code snippet. You may have noticed that INTERACTIVE_CATEGORY is set as category identifier while creating a category and the same we are passing here under “category” key in the payload.

Handling the Actions

To handle the actions performed by the user, we have to implement a delegate method in the AppDelegate Class, as follows:

-(void)application:(UIApplication *)application handleActionWithIdentifier:(NSString *)identifier forRemoteNotification:(NSDictionary *)userInfo completionHandler:(void (^)())completionHandler
{
        NSString *categoryIdentifier = [[userInfo objectForKey:@"aps"] objectForKey:@"category"];

       if ([categoryIdentifier isEqualToString:INTERACTIVE_CATEGORY])
       {
                if ([identifier isEqualToString:ACTION1_IDENTIFIER])
                {
                    NSLog(@"ACTION1 triggered");
                }
               else if ([identifier isEqualToString:ACTION2_IDENTIFIER])
              {
                   NSLog(@"ACTION2 triggered");
              }
             else if ([identifier isEqualToString:ACTION3_IDENTIFIER])
             {
                  NSLog(@"ACTION3 triggered");
             }
             else if ([identifier isEqualToString:ACTION4_IDENTIFIER])
             {          
                  NSLog(@"ACTION4 triggered");
             }
       }
      completionHandler();
}

The delegate method comes with an identifier of the action performed and the notification payload dictionary.

The categoryIdentifier from the push notification payload will help you know the actions category.
The next step is to compare the identifier that came in the above delegate method with action identifiers that were grouped in that category.

Once you have finished performing the specified action, then you must call completionHandler at the end of the delegate method. Failure to execute the completion handler block at the end of your implementation will cause your app to be terminated.

Analysts agree that a mix of emulators/simulators and real devices are necessary to optimize your mobile app testing - learn more in this white paper, brought to you in partnership with Sauce Labs.

Topics:
mobile ,mobile app development ,ios ,push notifications

Published at DZone with permission of Rajeev Ranjan. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}