Netmera Push Notification

Steps for Sending Your First Push Notification via Netmera

Step 1: Creating a Push Notification Certificate

Please follow the steps that are explained in the Apple’s App Distribution Guide, within the section named “Configuring Push Notifications”. You can find the resources here:

NOTE: In the last step (Installing Client SSL Signing Identity on the Server), you should export your certificate in .p12 format. Step 2: Upload Certificate to Netmera

You have created your APNS Certificate, and exported it as .p12 file. You can now upload the certificate to Netmera. Please go into “Settings” tab of your Netmera application in the Netmera panel, and upload your certificate and it’s password to one of the relevant sections—Development or Production. here is the screenshot of the related section of Netmera panel.

image_ios_tutorial_5

Step 3: Registering Device

By default, just by drag&dropping Netmera iOS SDK to your project and adding your Netmera api key into NetmeraSettings.plist file, SDK will handle all registration process to receive standard and rich push notifications.

If you want to monitor push registration process, you can implement two delegate methods which are stated below in your AppDelegate class:

/**
     * didRegisterForRemoteNotificationsWithDeviceToken method gives you a unique deviceToken that you will use it to address your notification while sending.
     */
    - (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
        // The device is permitted to receive push notifications.
    }

    /**
     * If customer disables push notifications or something else go wrong didFailToRegisterForRemoteNotificationsWithError notifies you.
     */
    - (void)application:(UIApplication *)app didFailToRegisterForRemoteNotificationsWithError:(NSError *)err {
        NSLog(@"Registration failed. Reason: %@", err.localizedDescription);
    }

3.1. Registering With Tags

You can register the devices to diverse tags by using the NMDeviceDetail class objects. These tags can be used to target the devices that will receive push notifications. The code below demonstrates process of registering to “News, and Sports” tags:

NMDeviceDetail *deviceDetail = [[NMDeviceDetail alloc] init];
    [deviceDetail addTags:@[@"News", @"Sports"]];

    [NMPushManager registerWithDeviceDetail:deviceDetail completionHandler:^(BOOL deviceDidRegister, NSError *error) {
        if (!error)
            NSLog(@"The device is registered successfully.");
        else
            NSLog(@"Error occurred. Reason: %@", error.localizedDescription);
    }];

Note that, if a device has been registered to some tags before, these new tags will be added to the previously registered tags. The code block below shows the process of adding a new tag called “Tech”.

[deviceDetail addTag:@"Tech"];

[NMPushManager registerWithDeviceDetail:deviceDetail completionHandler:^(BOOL deviceDidRegister, NSError *error) {
    if (!error)
        NSLog(@"The device is registered successfully.");
    else
        NSLog(@"Error occurred. Reason: %@", error.localizedDescription);
}];

The device is now registered to Sports, News, and Tech tags. If you use the following code instead of addTag: or addTags: methods:

//used in order to override previously registered tags 
[deviceDetail overrideTagsWithNewTags:@[@"Tech"]];

Previously-registered tags are removed and device would be only registered to only “Tech” tag.

3.2. Push Notifications and Custom Key-Value Pairs

You can also set custom key-value pairs over NMDeviceDetail object when registering a device. Therefore, if a push notification is sent for the specific custom field(s), the devices registered to them should automatically receive the message.

Custom Fields allows you to store and manage useful information about the device which runs your application. Custom Fields are a way to store user or device specific attributes in a key-value format. For example, by giving your user’s userID as the custom field, you can send push notifications to all devices of specified userIDs.

The developers should be aware of the fact that every time a device is registered with custom field(s), new key-value pair(s) overrides the current ones:

    NMDeviceDetail *deviceDetail = [[NMDeviceDetail alloc] init];
    deviceDetail.customDictionary = [[NSMutableDictionary alloc] init];
    [deviceDetail.customDictionary setObject:@"value1" forKey:@"key1"];
    [deviceDetail.customDictionary setObject:@"value2" forKey:@"key2"];

    [NMPushManager registerWithDeviceDetail:deviceDetail completionHandler:^(BOOL deviceDidRegister, NSError *error) {
        if (!error)
            NSLog(@"The device is registered successfully.");
        else
            NSLog(@"Error occurred. Reason: %@", error.localizedDescription);
    }];

If you just want to add a new key-value pair in the customDictionary instead of overriding it, you should first get custom dictionary information from Netmera, and change it manually:

[NMDeviceDetail getDeviceDetailWithCompletionHandler:^(NMDeviceDetail *deviceDetail, NSError *error) {
        if (!error)
        {NSLog(@"The device detail is obtained successfully. %@",deviceDetail.description);
            [deviceDetail.customDictionary setObject:@"value1" forKey:@"key1"];
            [deviceDetail.customDictionary setObject:@"value2" forKey:@"key2"];

            [NMPushManager registerWithDeviceDetail:deviceDetail completionHandler:^(BOOL deviceDidRegister, NSError *error) {
                if (!error)
                    NSLog(@"The device is registered successfully.");
                else
                    NSLog(@"Error occurred. Reason: %@", error.localizedDescription);
            }];

        }
        else
            NSLog(@"Error occurred. Reason: %@", error.localizedDescription);
    }];

3.3. Unregistering Devices

Netmera provides users with the ability to manage registered devices and tags.

  • Unregister from individual tags:
NMDeviceDetail *deviceDetail = [[NMDeviceDetail alloc] init];
[deviceDetail addTags:@[@"News", @"Tech"]];

[NMPushManager unregisterWithDeviceDetail:deviceDetail completionHandler:^(BOOL deviceDidUnregister, NSError *error) {
    if (!error)
        NSLog(@"The device is unregistered successfully.");
    else
        NSLog(@"Error occurred. Reason: %@", error.localizedDescription);
}];

Using the registration sample above where—News, Sports and Tech groups—were registered on the device, the unregister code block used, delists News and Tech groups from the device.

If Sports group is also unregistered, the device will be registered to only a Broadcast group.

3.4. Unregister From Tags Completely

  • Completely Unregister:

    To completely unregister a device, the method that can be used is unregistering without setting device tags for NMDeviceDetail.

[NMPushManager unregisterWithCompletionHandler:^(BOOL deviceDidUnregister, NSError *error) {
        if (!error)
            NSLog(@"The device is unregistered successfully.");
        else
            NSLog(@"Error occurred. Reason: %@", error.localizedDescription);
}];

3.5. Getting Device Information from Netmera

To get the registered tags or any other registration information currently active on a device, use the code block below:

[NMDeviceDetail getDeviceDetailWithCompletionHandler:^(NMDeviceDetail *deviceDetail, NSError *error) {
if (!error)
NSLog(@"The device detail is obtained successfully.");
else
NSLog(@"Error occurred. Reason: %@", error.localizedDescription);
}];

3.6. Getting the List of Available Tags from Netmera

You can also get all the tags on your application’s token list with the code block below:

[NMPushManager getDeviceTagsWithCompletionHandler:^(NSArray *tags, NSError *error) {
        if (!error)
            NSLog(@"The application registered tags is obtained successfully.");
        else
            NSLog(@"Error occurred. Reason: %@", error.localizedDescription);
}];

3.7. Further Information on Overriding and Adding

Overriding tags or adding them into the tag set is a choice which should be planned before adding them. When all of the tags should change when a user performs a certain action, overriding tags should be used. But otherwise, overriding tags would be considered as a dangerous behavior.

3.7.1. Adding and Overriding Tags

To add tags:

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

        NMDeviceDetail *deviceDetail = [[NMDeviceDetail alloc] init];
        [deviceDetail addTag:@"Tech"];

        [NMPushManager registerWithDeviceDetail:deviceDetail completionHandler:^(BOOL deviceDidRegister, NSError *error) {
            if (!error)
                NSLog(@"The device is registered successfully.");
            else
                NSLog(@"Error occurred. Reason: %@", error.localizedDescription);
        }];

This piece of code adds “Tech” tag in the on the device.

To override tags:

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

        NMDeviceDetail *deviceDetail = [[NMDeviceDetail alloc] init];
        [deviceDetail overrideTagsWithNewTags:@[@"Tech"]];

        [NMPushManager registerWithDeviceDetail:deviceDetail completionHandler:^(BOOL deviceDidRegister, NSError *error) {
            if (!error)
                NSLog(@"The device is registered successfully.");
            else
                NSLog(@"Error occurred. Reason: %@", error.localizedDescription);
        }];

This piece of code clears all of the tags on the device and adds @“Tech” tag on the device.

3.7.2. Adding and Overriding Custom Fields

To add custom fields:

    [NMDeviceDetail getDeviceDetailWithCompletionHandler:^(NMDeviceDetail *deviceDetail, NSError *error) {
        if (!error)
        {NSLog(@"The device detail is obtained successfully. %@",deviceDetail.description);
            [deviceDetail.customDictionary setObject:@"value1" forKey:@"key1"];
            [deviceDetail.customDictionary setObject:@"value2" forKey:@"key2"];

            [NMPushManager registerWithDeviceDetail:deviceDetail completionHandler:^(BOOL deviceDidRegister, NSError *error) {
                if (!error)
                    NSLog(@"The device is registered successfully.");
                else
                    NSLog(@"Error occurred. Reason: %@", error.localizedDescription);
            }];

        }
        else
            NSLog(@"Error occurred. Reason: %@", error.localizedDescription);
    }];

This piece of code adds key1:value1 and key2:value2 key-value pairs in the “Custom Dictionary” of the NMDeviceDetail.

To override custom fields:

    NMDeviceDetail *deviceDetail = [[NMDeviceDetail alloc] init];
    deviceDetail.customDictionary = [[NSMutableDictionary alloc] init];
    [deviceDetail.customDictionary setObject:@"value1" forKey:@"key1"];
    [deviceDetail.customDictionary setObject:@"value2" forKey:@"key2"];

    [NMPushManager registerWithDeviceDetail:deviceDetail completionHandler:^(BOOL deviceDidRegister, NSError *error) {
        if (!error)
            NSLog(@"The device is registered successfully.");
        else
            NSLog(@"Error occurred. Reason: %@", error.localizedDescription);
    }];

This piece of code clears the customDictionary of the device detail and adds key1:value1 and key2:value2 key-value pairs in the “Custom Dictionary” of the NMDeviceDetail.

Step 4: Handling Push Notifications

Handling push notifications can be done easily with NMPushManagerDelegate Protocol. Rich Push Notifications and Interactive Push Notifications are handled automatically by the SDK. However if you want to handle push notifications manually; for example if you want to display a standard push notification while the application is in foreground or present the rich push inbox in another view, you should override the delegate methods of the NMPushManagerDelegate Protocol.

Before getting into the NMPushManagerDelegate Protocol, let’s see how Netmera SDK handles push notifications in default:

a. Standard Push Notifications

  • When Application is Closed or in Background:

    Push is received normally. User may open the application by sliding the notification.

  • When Application is in Foreground:

    Nothing happens unless you add code to manually handle standard push notifications which is received in foreground.

b. Rich Push Notifications

  • When Application is Closed or in Background:

    Push is received normally. User may open the application by sliding the notification. When user opens the application, NMPushInbox is shown automatically(modally).

  • When Application is in Foreground:

    NMPushInbox is shown automatically(modally).

c. Interactive Push Notifications

  • When Application is Closed or in Background:

    Push is received normally. User interacts with the application by selecting one of the two choices which are presented in the notification (by sliding the notification to left). Application can take different actions based on the action of the user.

  • When Application is in Foreground:

    The title, text and buttons of the interactive push notification is presented in an UIAlertView. User interacts with the application by selecting one of the two choices which are presented in the UIAlertView. Application can take different actions based on the action of the user.

IMPORTANT NOTE: Currently, if a push notification sent from Netmera is received, default remote notification delegate methods are also called in addition to NMPushManagerDelegate protocol methods. This behavior will be changed in the next major release! If the push notification is sent via Netmera, only NMPushManagerDelegate methods will be called. Therefore, you should update your code and start to use NMPushManagerDelegate methods to manage push notifications coming from Netmera.

Following are the methods and their explanations:

/**
 *  Called whenever a push notification is received. This method will NOT be called if didReceivePush:appState:fetchCompletionHandler: method is implemented.
 *
 *  @param push Push object that is received. It may be an NMPushObject or an NMRichPushObject. You can check via type property of NMPushObject class.
 *  @param state An enum value that describes the state when app has received given push notification. For possible values, see NMAppState.
 *
 *  @note You can implement this method instead of didReceivePush:appState:fetchCompletionHandler: if you do not enable "remote-notification" background mode.
 */
- (void)didReceivePush:(NMPushObject*)push appState:(NMAppState)state;

/**
 * @brief Called whenever a push notification is received. This method overrides didReceivePush:appState: method.
 *
 * @param push Push object that is received. It may be an NMPushObject or an NMRichPushObject. You can check via type property of NMPushObject class.
 * @param state An enum value that describes the state when app has received given push notification. For possible values, see NMAppState.
 * @param completionHandler You should call the completionHandler as soon as you're finished your task, so the system can accurately estimate its power and data cost.
 *
 * @note You should implement this method if you enable "remote-notification" background mode.
 */
- (void)didReceivePush:(NMPushObject*)push appState:(NMAppState)state fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))completionHandler;

/**
 * @brief Called when your app has been activated by the user via selecting an action from an interactive push notification. You can check push.actionIdentifier value to get action identifier of the touched action button.
 *
 * @param push Push object that is received. You can get parameters set to the action from Netmera panel via push.actionParams property.
 * @param state An enum value that describes the state when app has received given push notification. For possible values, see NMAppState.
 * @param completionHandler You should call the completion handler as soon as you've finished handling the action.
 *
 * @note You should implement this method if you are using interactive notifications in your application.
 */
- (void)handleActionForPush:(NMPushObject*)push appState:(NMAppState)state completionHandler:(void(^)())completionHandler;

/**
 * Method that asks whether received rich push notification should be presented by Netmera SDK automatically.
 * @note If you do NOT implement this method, SDK will automatically present received rich push notifications considering preferences set in NetmeraSettings.plist file. You should implement this method and return NO if you want to handle presentation of received rich push notications yourself.
 * @param richPush Rich push object that is received.
 * @return A boolean value which determines if given rich push should be presented by SDK automatically.
 */
- (BOOL)shouldPresentRichPush:(NMRichPushObject*)richPush;

/**
 *  If an interactive push is received when app is foreground, SDK present an alert containing action buttons to user by default. To disable this, implement this method and return NO.
 *
 *  @param push Received interactive push notification.
 *
 *  @return Boolean value to determine if SDK should automatically present an alert.
 */
- (BOOL)shouldPresentInteractivePushInForeground:(NMPushObject*)push;
a. Below is a piece of code which is needed to display standard push notifications in foreground:

- (void)didReceivePush:(NMPushObject*)push appState:(NMAppState)state
{
    if(push.type == NMNotificationTypeStandard && state ==  NMAppStateWasInForeground)
    {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Push Notification"
                                                            message:[push alertText]
                                                           delegate:nil
                                                  cancelButtonTitle:@"OK"
                                                  otherButtonTitles:nil];
        [alertView show];

    }

}

b. Handling interactive push notifications which contain action parameters requires the implementation of another delegate method, Below is a simple implementation of this delegate method.

/**
 * @brief Called when your app has been activated by the user via selecting an action from an interactive push notification. You can check push.actionIdentifier value to get action identifier of the touched action button.
 *
 * @param push Push object that is received. You can get parameters set to the action from Netmera panel via push.actionParams property.
 * @param state An enum value that describes the state when app has received given push notification. For possible values, see NMAppState.
 * @param completionHandler You should call the completion handler as soon as you've finished handling the action.
 *
 * @note You should implement this method if you are using interactive notifications in your application.
 */
- (void)handleActionForPush:(NMPushObject *)push appState:(NMAppState)state completionHandler:(void (^)())completionHandler
{
    //Check action identifier
    if([push.actionIdentifier isEqualToString:@"AcceptButton"])
    {
        //TODO: Show information about accepted content.
    }
    else if([push.actionIdentifier isEqualToString:@"DeclineButton"])
    {
        //TODO: Send decline request to server.
    }
    else if([push.actionIdentifier isEqualToString:@"ReplyButton"])
    {
        //TODO: Open mail reply screen.
    }
    else if([push.actionIdentifier isEqualToString:@"MarkAsReadButton"])
    {
        //TODO: Send mark as read request to server.
    }

    //Here you could get parameters related to selected action which are set in Netmera panel using push.actionParams property

    NSLog(@"Action Parameters : %@",push.actionParams);

    //You should always call completionHandler when you are finished.
    completionHandler();
}

Action parameters helps you to answer user’s response to your interactive push notification.

c. You are also free while you are handling Rich Push Notifications :

The “Rich Push Notification” feature is one that provides developers with the ability to send content in an HTML or URL format. This feature allows you to send well designed HTML pages to your app users as push notifications.

The instructions—stated in previous steps—that enable a device to receive push notifications—such as registering etc.—remain valid for utilizing the Rich Push Notification feature. You can easily enable this feature and send HTML themed notifications just by adding Netmera iOS SDK. Then everything is handled by SDK itself automatically.

While the application is on the background or not running, alert text of receiving rich push is displayed as a banner automatically by Apple, again and if you click the push notification, the application opens, you see firstly a loading indicator (it is not be displayed while the application is on foreground, since we do not want to sever application action flow.) and then rich push notification as a webview on the screen. However, while the application is on the foreground, rich push notification is displayed automatically by Netmera iOS SDK when the application is opened, but you can optionally change this action. Therefore, you see first text message as an alert, click the show button and see rich push notification. You can even ignore all rich push notifications coming while the application is only on foreground. This is beneficial while the application has important tasks when the user should not be distracted by any other task, i.e. the user performing purchase process. All these configurations can be adjusted from NetmeraSettings.plist.

Handling Rich Push Notification can be done through:

- (BOOL)shouldPresentRichPush:(NMRichPushObject*)richPush;

delegate method, display the rich push or the rich push inbox manually and return NO to prevent Netmera SDK from automatically displaying the rich push object.

NOTE: By default, when a rich push notification is received, Netmera SDK shows a “RichPushViewController” modally on the currently visible controller. So you don’t need to set a parent controller.

In order for this feature to work appropriately, you need to set the root view controller of your application in your “AppDelegate” class like this:

window.rootViewController = YOUR_ROOT_CONTROLLER;

Note: If you add your rootViewController’s view as a sub view to your window –like, [window addSubview:YOUR_ROOT_CONTROLLER.view]—, RichPushViewController won’t be shown. Step 5: Managing Button Sets For Interactive Push Notifications

Enabling interactive push notifications for your device is very simple. You only need to call [NMPushManager setUserNotificationCategories:] method with an NSSet containing UIUserNotificationCategory objects. Netmera will automatically register the app for given categories, and synchronize Netmera panel with your button sets. Here is a simple example that you can call in any place (application:didFinishLaunchingWithOptions: is the recommended place):

//This check is needed if your application supports iOS 7 or before.
    if([[UIApplication sharedApplication] respondsToSelector:@selector(registerUserNotificationSettings:)])
    {
        //FIRST CATEGORY (Accept/Decline Button Set)
        UIMutableUserNotificationAction *action1 = [[UIMutableUserNotificationAction alloc] init];
        action1.identifier = @"AcceptButton";
        action1.title = @"Accept";
        action1.activationMode = UIUserNotificationActivationModeForeground;

        UIMutableUserNotificationAction *action2 = [[UIMutableUserNotificationAction alloc] init];
        action2.identifier = @"DeclineButton";
        action2.title = @"Decline";
        action2.activationMode = UIUserNotificationActivationModeForeground;
        //To show a destructive button.
        action2.destructive = YES;

        UIMutableUserNotificationCategory *acceptDecline = [[UIMutableUserNotificationCategory alloc] init];
        //This identifier string will be visible in Netmera panel.
        acceptDecline.identifier = @"AcceptDeclineAction";

        //Setting actions for UIUserNotificationActionContextMinimal is enough. SDK will automatically add related action for UIUserNotificationActionContextDefault also.
        //PS: Netmera currently NOT supports having more than two actions. So, you can NOT use different action sets for different contexts.
        [acceptDecline setActions:@[action1, action2] forContext:UIUserNotificationActionContextMinimal];

        //SECOND CATEGORY (Reply/Mark As Read Button Set)
        UIMutableUserNotificationAction *action3 = [[UIMutableUserNotificationAction alloc] init];
        action3.identifier = @"ReplyButton";
        action3.title = @"Reply";
        action3.activationMode = UIUserNotificationActivationModeForeground;

        UIMutableUserNotificationAction *action4 = [[UIMutableUserNotificationAction alloc] init];
        action4.identifier = @"MarkAsReadButton";
        action4.title = @"Mark As Read";
        //This tells that application will not be opened when Mark As Read button is selected.
        //It will only wake the application in background mode.
        action4.activationMode = UIUserNotificationActivationModeBackground;

        UIMutableUserNotificationCategory *mailCategory = [[UIMutableUserNotificationCategory alloc] init];
        mailCategory.identifier = @"MailReplyAction";
        [mailCategory setActions:@[action4, action3] forContext:UIUserNotificationActionContextMinimal];

        //Registers the device to related interactive notification categories.
        [NMPushManager setUserNotificationCategories:[NSSet setWithObjects:acceptDecline, mailCategory, nil]];
    }

Step 6: Getting the Details of the Push Notification

Although the limitation on the maximum amount of data which can be transmitted with a push notification is increased in iOS 8, Netmera does not send the push notification object completely, you should use [NMPushObject fetchPushDetailsWithCompletionHandler:] method and use the data in the completion handler.

Payload information specified as key-values pairs can be with relevant push notification messages, by setting the needed values in the boxes provide for them on the Netmera Create Campaigns screen. This allows you to include additional information to your push notifications while sending them out. You can use push.customParams in the completion handler of the [NMPushObject fetchPushDetailsWithCompletionHandler:] method to access those key-value pairs.

This piece of code ( an override of [NMPushManagerDelegate didReceivePush: appState:] ) can help you to understand when and how to use [NMPushObject fetchPushDetailsWithCompletionHandler:] method:

- (void)didReceivePush:(NMPushObject*)push appState:(NMAppState)state
{
    NSLog(@"Before:");
    NSLog(@"Send Date: %@",push.sendDate.description);
    NSLog(@"Alert Text: %@",push.alertText.description);
    NSLog(@"Event Custom Parameters: %@",push.eventCustomParams.description);
    NSLog(@"Custom Parameters: %@", push.customParams.descriptionInStringsFileFormat);
    NSLog(@"NotificationID: %@",push.notificationId.description);
    NSLog(@"Create Date: %@",push.createDate.description);
    NSLog(@"Expiration Date: %@",push.expirationDate.description);
    NSLog(@"Type: %u",push.type);
    NSLog(@"Push Inbox Status: %u",push.pushInboxStatus);
    NSLog(@"Category:%@",push.category.description);
    NSLog(@"Push Logo URL: %@",push.pushLogoURL.description);
    NSLog(@"Push Inbox Status: %u",push.pushInboxStatus);

    [push fetchPushDetailsWithCompletionHandler:^(NSError *error) {

        if (!error)
        {
            if(push.type == NMNotificationTypeStandard)
            {

                if(state != UIApplicationStateBackground)
                {
                    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Push Notification"
                                                                    message:[push alertText]
                                                                   delegate:nil
                                                          cancelButtonTitle:@"OK"
                                                          otherButtonTitles:nil];
                    [alertView show];
                }
            }

        }
        else
            NSLog(@"Error occurred. Reason: %@", error.localizedDescription);

        NSLog(@"After:");
        NSLog(@"Send Date: %@",push.sendDate.description);
        NSLog(@"Alert Text: %@",push.alertText.description);
        NSLog(@"Event Custom Parameters: %@",push.eventCustomParams.description);
        NSLog(@"Custom Parameters: %@", push.customParams.descriptionInStringsFileFormat);
        NSLog(@"NotificationID: %@",push.notificationId.description);
        NSLog(@"Create Date: %@",push.createDate.description);
        NSLog(@"Expiration Date: %@",push.expirationDate.description);
        NSLog(@"Type: %u",push.type);
        NSLog(@"Push Inbox Status: %u",push.pushInboxStatus);
        NSLog(@"Category:%@",push.category.description);
        NSLog(@"Push Logo URL: %@",push.pushLogoURL.description);
        NSLog(@"Push Inbox Status: %u",push.pushInboxStatus);
    }];

}

Step 7: Push Notification Sounds

Netmera provides you with the features required to send push notifications with particular sounds to devices running your apps. This can be done by enabling the sound feature from the Setup tab of Create Campaign section.

There are three states for “ADD NOTIFICATION SOUND FOR iOS” field, which controls sound feature. These three states are:

  • “Default”: This value enables the phone to play the current default notification sound when receiving the push notification from your application. In this situation, no extra work is needed.

  • “Silence.wav”: Your application does not play any sound when receiving your notification.

  • “your_sound_name”: You can specify any sound to be played when receiving the push notification. To perform this function, you should pay attention to some constraints. One of them is that your sound file should be included in your main bundle. If this condition does not meet, default sound of your phone will be played when receiving the push notification, instead. Another constraint is that you can use just the audio data packaged in an ‘aiff’, ‘wav’ or ‘caf’ file (i.e. your_sound_name.aiff). Last constraint is that you can add at most 30-seconds-length custom sounds. If any sound exceeds 30 seconds, the default sound of your phone will be played instead of your custom one. You can select any sound name in the drop-box menu. All items in the menu are the sound files which extensions satisfy the push sound extensions (.aiff, .wav and .caf).

It is important to note that the states mentioned above are valid or occur when your app is at the background of a devices interface or not currently being run. But if your app is currently being run on a devices interface/display screen, all sent information—such as sound, alerts or payload—will be sent within the user’s info thereby eliminating sounds.

Alternatively, you can also enable notification sounds even if your app is being currently run on the foreground of a device with the “applications: didRecieveRemoteNotification:” method class as shown below:

// You should also check application state if you donot want // to play notification sound two times when your application //is on background.
if (![[notificationSound objectAtIndex:0] isEqual:@"default"]) {
      NSString *notificationSoundName = [notificationSound objectAtIndex:0];
      NSLog(@"Notification sound name : %@", notificationSoundName);
      NSString *notificationSoundType = [notificationSound objectAtIndex:1];
      NSLog(@"Notification sound type : %@", notificationSoundType);
      NSString *notificationSoundPath = [[NSBundle mainBundle] pathForResource:notificationSoundName ofType:notificationSoundType];
      NSURL *notificationSoundURL = [NSURL fileURLWithPath:notificationSoundPath];
      AudioServicesCreateSystemSoundID((__bridge CFURLRef)notificationSoundURL, &_notificationSound); // _notificationSound is a property.
      AudioServicesPlaySystemSound(self.notificationSound);
}

NOTE: All sound names in the drop-box menu are received from your main bundle by Netmera iOS SDK automatically. However, you should pay attention on significant point. After changing or removing a current sound file, and cleaning the project, new built product actually updates its contents (It is valid in case of renaming, it renames sound file correctly, and remove old one). During deployment of product to simulator or any device, XCode somehow does not check or detect renaming, it persists old sound file, but also add newly-renamed file, so there will be 2 different files in the actual product. Therefore, SDK sends both names to Netmera and you will see them in the drop-down menu for push sound files. Both sound names can be used while sending push notifications, it will not crash the application even if it does not exist in the main bundle. In order to remove old sound files from the device or simulator, developer should uninstall application from device/simulator. There is no other way for now. Step 8: Push Inbox for Rich Push Notifications

“Push Inbox” is a feature, which gives app users the opportunity to store and redisplay rich push notifications via an interface in your application. By default, this feature is enabled by the SDK, which means all coming rich push notifications are shown as if they are opened from inbox. In order to disable push inbox feature in your application, you can simply set NO for pushInboxEnabled flag NetmeraSettings.plist or call below method:

[Netmera setPushInboxEnabled:NO];

You can also enable the ability to open Push inbox while a custom action occurs—touch event of a button—by utilizing the call method below:

[NMPushManager presentPushInboxFromController:YOUR_CONTROLLER];

By default, this method presents a modal controller which shows the list of rich push notifications that have been sent to your phone. Additionally, all controllers related to push inbox are open source, so that you can change the default ones or use your custom ones if you like. You can find the related source codes under NetmeraSDK/Resources folder.

Moreover, Push inbox of your application is available when the internet connection is lost, however, you should access to Internet in order to display rich push notifications.

Step 9: Automatic Badge Increment

You can add iOS badges to your application icon when receiving rich push notifications, while plain push notifications do not change badge number. In order to achieve this, you do not need to make any changes in your code. All that is needed is for you to prepare your own rich push notification in the “Campaigns” tab on the Netmera website.

If you like to use a badge, you should activate badge increment in the “Setup” panel of “Create Campaign” section. If your user does not read the incoming rich push, a badge number will be displayed on your application icon.

Current push inbox controller of Netmera IOS SDK also gives your users the opportunity to change badge numbers manually by simply marking received rich push notifications as read, or as unread, or by deleting from push inbox. This feature guarantees that your users will recieve your rich push notifications.

Step 10: Deep linking Mechanism (New Feature for navigation)

Note: You should use Netmera IOS SDK version 2.5 or above for this feature.
Deep linking enables your application to open specific screens upon actions taken from push notifications. To enable deep linking for your application, you should define a custom url scheme specific to your application following these steps:

10.1- Select your project target and navigate “Info” tab.

deeplink_1


10.2- Expand “URL Types title and click + button on the bottom left corner to add a URL Type.


deeplink_2


10.3- Provide a value for “Identifier” field. This can be any value, but the convention is to use a “reverse domain name” as the bundle identifier of your project (i.e. “com.netmera.CustomURLSchemesTestProject”).

deeplink_3


10.4- For “URL Schemes” field, set a lowercase string unique to your application (i.e. the last component of your bundle identifier).

Here is an example deep link pattern which is created from Netmera panel:

yourscheme://yourhost?productId={productId}&productCategory={productCategory}

You can handle above link with the following code snippet:

-(BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString*)sourceApplication annotation:(id)annotation {
	if (![[url scheme] isEqualToString:@"yourscheme"]) { 
		return NO; 
	} 
	NSURLComponents *components = [NSURLComponents componentsWithString:url.absoluteString];
	//Identifier that indicates which screen to present.
	NSString *deepLinkIdentifier = [components host];
	
	//Array of NSURLQueryItem objects that contains key-value parameter pairs 
	NSArray *params = [components queryItems];
	
	// Here you can decide which screen to present according to deepLinkIdentifier variable, and you can inject sent 
	// parameters to the view controller to be presented either by using key-value coding or manually.
	// 
	//	*
	//	*
	//	*
	return YES; 
}

Step 11: Testing Push Notifications Before Sending

In order to test your push campaigns before sending them to your target users, you can add some of your devices into the test group and simulate your campaign in advance. For this to be implemented, you should just register your application to a custom URL scheme and for that scheme to be used to add the relevant device into the test group with a link that have to be clicked on the device in a received mail from Netmera.

Registering a custom URL scheme is done with the info.plist (By default, projectName-Info.plist) file located in your application's project folder. In XCode, you can edit it directly in "Info" tab of target settings or using info.plist in graphical mode or text mode. Fore more information about "Custom URL Schemes", you can look at "Implementing Custom URL Schemes" title from the following link here.

Below you can see the steps regarding how to register a Custom URL Schemes from XCode "Info" tab of target settings.

Step1: Select your project target and navigate "Info" tab.

URL_Scheme_1

Step2: Expand "URL Types title and click + button on the bottom left corner to add a URL Type.

URL_Scheme_2

Step3: Provide a value for "Identifier" field. This can be any value, but the convention is to use a "reverse domain name" as the bundle identifier of your project (i.e. "com.netmera.CustomURLSchemesTestProject").

URL_Scheme_3

Step4: For "URL Schemes" field, you need to get your application's name from Netmera panel. Open your Netmera application, and take your application's name from URL like this:

Screen-Shot-2014-04-01-at-10.35.01

Then you should write the string "nm{YOUR_APPLICATION_NAME}" into "URL Schemes" field. For this example, the value should be "nmurlschemetest".

Final form of registered URL Scheme should be like this:

URL_Scheme_5

March 31, 2015 / parag