Mobile SDK iOS: EPZPushNotificationService

From ePrize Developers Wiki

Revision as of 15:32, 7 November 2014 by Anthony-hessler (Talk | contribs)
(diff) ←Older revision | Current revision (diff) | Newer revision→ (diff)
Jump to: navigation, search

Contents

Overview

The EPZPushNotificationService class is a Singleton class that provides the necessary logic to interface a user's device with the HelloWorld Push Notification Service. It provides the methods to subscribe/unsubscribe a device, retrieve and save push notification preferences, retrieve full notification data, and even record custom actions taken for specific notifications.

To be able to successfully subscribe a device and achieve full integration with the service, your application must be set up with Push Notification support, and must have access to the device token, as gleaned from the application:didRegisterForRemoteNotificationsWithDeviceToken: application delegate method.

Since this class is a Singleton, you will not create an instance of it. Rather, you will simply reference the sharedService property to access the data (properties) stored within the class, and methods to be called from the class.

For example, to set the push key:

[[EPZPushNotificationService sharedService] setPushKey:@"your_push_key_here"];

...or to fetch a user's push notification preferences:

[[EPZPushNotificationService sharedService] fetchPushNotificationPreferences:^(NSDictionary *data, NSError *error) {
    // Handle response here...
}

Tasks

Getting the Shared Service Instance
+ sharedService

Handling Subscriptions
- userIsSubscribed
- subscribeUserWithDeviceToken:callback:
- unsubscribeUser:

Accessing & Saving Push Notification Preferences
- fetchPushNotificationPreferences:
- savePushNotificationPreferences:
- pushPreferenceItemForKey:
  pushNotificationPreferences property

Retrieving Notification Data
- fetchAdditionalNotificationDataForPayloadID:callback:

Recording Actions for Notifications
- recordActionForPushNotificationID:withValue:forAction:callback:

Accessing Device Token
  deviceToken property

Accessing Configurable Items
  pushKey property
  appID property


Properties

pushKey

The push key used by your application.

@property (nonatomic, copy) NSString *pushKey

Discussion
The push key is used as a unique key for all methods interfacing with the HelloWorld servers. This value should be set in your App Delegate (in the application:didFinishLaunchingWithOptions: method, for instance) so it is ready to use anywhere in your code.

Declared In
EPZPushNotificationService.h



appID

The application's bundle ID value.

@property (nonatomic, copy) NSString *appID

Discussion
The appID value is optional to configure, and will default to the application's package name value (e.g. "com.helloworld.mobilesdk.pushdemo"). This value MUST be configured with HelloWorld in order to work properly in the application. If a value is used that not properly configured, the app will not be able to successfully integrate with the SDK's Push Notification Service.

Declared In
EPZPushNotificationService.h



deviceToken

The string value of the device token. (read-only)

@property (nonatomic, readonly) NSString *deviceToken

Discussion
This property returns the string value of the device token, as set in the subscribeUserWithDeviceToken:callback: method. It is in place as a convenience method and has little use outside of the core SDK logic.

Declared In
EPZPushNotificationService.h



pushNotificationPreferences

A dictionary of EPZPushPreferenceItem objects. (read-only)

@property (nonatomic, readonly) NSDictionary *pushNotificationPreferences

Discussion
This property is a convenience to return a dictionary of EPZPushPreferenceItem objects. This dictionary is set after successful retrieval of a user's push notification preferences, as gleaned from the fetchPushNotificationPreferences: method.

Declared In
EPZPushNotificationService.h


Class Methods

sharedService

Returns the singleton library instance.

+ (EPZPushNotificationService *) sharedService

Declared In
EPZPushNotificationService.h


Instance Methods

pushPreferenceItemForKey:

Returns an EPZPushPreferenceItem for the specified key.

- (EPZPushPreferenceItem *) pushPreferenceItemForKey:(NSString *)key

Parameters

key
The preferenceID value for a specific EPZPushPreferenceItem.

Discussion
This is a convenience method to retrieve a specific EPZPushPreferenceItem for a given key. It will return nil if the specified key is not associated with any of the pushNotificationPreferences.

Declared In
EPZPushNotificationService.h



userIsSubscribed

Returns a boolean flag for whether or not the user's device is subscribed with the EPZPushNotificationService.

- (BOOL) userIsSubscribed

Discussion
This is a convenience method that can be used to return whether or not the user's device is already subscribed with the EPZPushNotificationService. It is advisable to make use of this method before attempting to subscribe and/or unsubscribe the device.

Declared In
EPZPushNotificationService.h



subscribeUserWithDeviceToken:callback:

Subscribes the device with the EPZPushNotificationService.

- (void) subscribeUserWithDeviceToken:(NSData *)deviceToken callback:(void(^)(NSError *error))callbackBlock

Parameters

deviceToken
The device token, as gleaned from the application:didRegisterForRemoteNotificationsWithDeviceToken: application delegate method.
callbackBlock
A block that is called upon completion of the subscribe request. The block’s argument is an NSError, which will be nil unless the call is unsuccessful.

Discussion
This method makes an asynchronous request to subscribe a user's device with the HelloWorld Push Notification Service.

Since the block callback is used for both success and error events, it is advisable to implement a conditional check for the error object in your callback block, like in the code sample below. It is also advisable to only call this method if a NO value is returned from userIsSubscribed.

// AppDelegate.m
- (void) application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    if (![EPZPushNotificationService sharedService].userIsSubscribed) {
        [[EPZPushNotificationService sharedService] subscribeUserWithDeviceToken:deviceToken callback:^(NSError *error) {
            if (error) {
                // Error subscribing user. Handle error as needed.
            } else {
                // User successfully subscribed. Safe to call the fetchPushNotificationPreferences: method
            }
        }];
    }
}

Declared In
EPZPushNotificationService.h



unsubscribeUser:

Unsubscribes the device from the EPZPushNotificationService.

- (void) unsubscribeUser:(void(^)(NSError *error))callbackBlock

Parameters

callbackBlock
A block that is called upon completion of the unsubscribe request. The block’s argument is an NSError, which will be nil unless the call is unsuccessful.

Discussion
This method makes an asynchronous request to unsubscribe a user's device from the HelloWorld Push Notification Service.

Since the block callback is used for both success and error events, it is advisable to implement a conditional check for the error object in your callback block, like in the code sample below. It is also advisable to only call this method if a YES value is returned from userIsSubscribed.

if ([EPZPushNotificationService sharedService].userIsSubscribed) {
    [[EPZPushNotificationService sharedService] unsubscribeUser:^(NSError *error) {
        if (error) {
            // Error unsubscribing user. Handle error as needed.
        } else {
            // User successfully unsubscribed.
        }
    }];
}

Declared In
EPZPushNotificationService.h



fetchPushNotificationPreferences:

Retrieve a user's push notification preferences.

- (void) fetchPushNotificationPreferences:(void(^)(NSDictionary *data, NSError *error))callbackBlock

Parameters

callbackBlock
A block that is called upon completion of the fetch request. The block’s arguments are an NSDictionary of EPZPushPreferenceItem objects (populated if successful) and an NSError (nil unless unsuccessful).

Discussion
This method makes an asynchronous request to fetch a user's push notification preferences from the HelloWorld Push Notification Service. When successful, the push notification preferences are saved in the pushNotificationPreferences property, and for convenience, are passed in to the callback block as the "data" argument.

Since the block callback is used for both success and error events, it is advisable to implement a conditional check for the error object in your callback block, like in the code sample below.

[[EPZPushNotificationService sharedService] fetchPushNotificationPreferences:^(NSDictionary *data, NSError *error) {
    if (error) {
        // Handle error as needed.
    } else {
        // Successfully retrieved push notification preferences.
    }
}];

Declared In
EPZPushNotificationService.h



savePushNotificationPreferences:

Saves a user's push notification preferences.

- (void) savePushNotificationPreferences:(void(^)(NSError *error))callbackBlock

Parameters

callbackBlock
A block that is called upon completion of the save request. The block’s argument is an NSError, which will be nil unless the call is unsuccessful.

Discussion
This method makes an asynchronous request to save a user's push notification preferences with the HelloWorld Push Notification Service.

Since the block callback is used for both success and error events, it is advisable to implement a conditional check for the error object in your callback block, like in the code sample below.

Note: This method uses the preference values stored in the pushNotificationPreferences property, which are automatically updated when a user changes a preference value in the SDK's built-in EPZPushPreferencesViewController. As such, for custom implementations of displaying push preferences to the user (e.g. not using the built-in EPZPushPreferencesViewController, you will need to ensure you accurately keep track of value updates for each EPZPushPreferenceItem that is stored in the pushNotificationPreferences property.
[[EPZPushNotificationService sharedService] savePushNotificationPreferences:^(NSError *error) {
    if (error) {
        // Handle error as needed.
    } else {
        // Successfully saved push notification preferences.
    }
}];

Declared In
EPZPushNotificationService.h



fetchAdditionalNotificationDataForPayloadID:callback:

Fetch additional notification data for the specified notification ID.

- (void) fetchAdditionalNotificationDataForPayloadID:(NSString *)remotePayloadID callback:(void(^)(NSDictionary *data, NSError *error))callbackBlock

Parameters

remotePayloadID
The notification ID used to retrieve corresponding notification data. This value is included in the initial remote notification's "userInfo" dictionary, as seen in the code sample below.
callbackBlock
A block that is called upon completion of the fetch request. The block’s arguments are an NSDictionary of the full remote notification payload (populated if successful) and an NSError (nil unless unsuccessful).

Discussion
This method makes an asynchronous request to save a user's push notification preferences with the HelloWorld Push Notification Service.

Since the block callback is used for both success and error events, it is advisable to implement a conditional check for the error object in your callback block, like in the code sample below. (Note: The code sample uses Constant values for the userInfo keys, as defined in EPZConstants.)

// AppDelegate.m
- (void) application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    // Check notification userInfo for remote payload ID and fetch additional notification data, if found.
    NSString *remotePayloadID = [[userInfo objectForKey:EPZ] objectForKey:EPZ_PUSH_KEY_PAYLOAD_ID];
    if (remotePayloadID) {
        [[EPZPushNotificationService sharedService] fetchAdditionalNotificationDataForPayloadID:remotePayloadId callback:^(NSDictionary *data, NSError *error) {
            if (error) {
                // Handle error as needed.
            } else {
                // Additional notification data successfully retrieved. Handle data as needed.
                NSString *payloadID = [NSString stringWithFormat:@"%@", data objectForKey:EPZ_PUSH_KEY_PAYLOAD_ID]];
                NSString *msgType = [NSString stringWithFormat:@"%@", data objectForKey:EPZ_PUSH_KEY_TYPE]];
                NSString *msgContent = [NSString stringWithFormat:@"%@", data objectForKey:EPZ_PUSH_KEY_CONTENT]];
                if ([msgType isEqualToString:EPZ_PUSH_KEY_PLAIN_TEXT]) {
                    // Notification type = plainText. Handle as needed.
                } else if ([msgType isEqualToString:EPZ_PUSH_KEY_RICH_TEXT]) {
                    // Notification type = richText. Handle as needed.
                } else if ([msgType isEqualToString:EPZ_PUSH_KEY_URL]) {
                    // Notification type = url. Handle as needed (e.g. launch URL using EPZWebViewController])
                } else if ([msgType isEqualToString:EPZ_PUSH_KEY_JSON]) {
                    // Notification type = json. Handle as needed (e.g. convert json to NSDictionary)
                }
            }
        }];
    }
}

Each set of data retrieved from the fetchAdditionalNotificationDataForPayloadID:callback: method will have a structure similar to that in the code snippets below (one code snippet per "type" of notification). Note that the main content of the notification data is found in the "content" key.

{
    content = "{"plainText": "This is some plain text in a JSON block.", "url": "http://helloworld.com"}";
    remotePayloadId = 4;
    type = json;
}

{
    content = "This is some plain text.";
    remotePayloadId = 8;
    type = plainText;
}

{
    content = "This is some <b>rich</b> text.";
    remotePayloadId = 15;
    type = richText;
}

{
    content = "http://www.helloworld.com";
    remotePayloadId = 16;
    type = url;
    openInNativeBrowser = 0;
}
Important Note:
Since the SDK is the bridge between your application and the HelloWorld Push Notification Service which dispatches the data, it is ultimately your responsibility to handle and parse this data as necessary for your application instance, as the SDK makes no assumptions about the data's key/value pairs from this method. That said, while the SDK doesn't make any assumptions on behalf of your application, it does provide the following Constant values for commonly used keys, as defined in EPZConstants:
  • EPZ_PUSH_KEY_CONTENT - Key for accessing the "content" object in the remote notification data object.
  • EPZ_PUSH_KEY_PAYLOAD_ID - Key for accessing the "remotePayloadId" object in the remote notification data object.
  • EPZ_PUSH_KEY_TYPE - Key for accessing the "type" object in the remote notification data object.
  • EPZ_PUSH_KEY_JSON - Key for the notification type "json".
  • EPZ_PUSH_KEY_PLAIN_TEXT - Key for the notification type "plainText".
  • EPZ_PUSH_KEY_RICH_TEXT - Key for the notification type "richText".
  • EPZ_PUSH_KEY_URL - Key for the notification type "url", or any URL value associated with the notification.
  • EPZ_PUSH_KEY_OPEN_IN_NATIVE_BROWSER - Key for a boolean flag that can be used to alert your application as to whether a URL should open in the device's native browser or the SDK's built-in EPZPromoWebViewController.
  • EPZ_PUSH_KEY_CLASS_NAME - Key for a class name which can be used to reference a specific class/view your app should present in response to receiving the notification.

Declared In
EPZPushNotificationService.h



recordActionForPushNotificationID:withValue:forAction:callback:

Records an action (event) for a specific notification ID.

- (void) recordActionForPushNotificationID:(NSString *)remotePayloadID withValue:(NSString *)value forAction:(NSString *)action callback:(void(^)(NSDictionary *data, NSError *error))callbackBlock

Parameters

remotePayloadID
The remote notification payload ID value, as gleaned from the initial remote notification.
value
The value of the action to record. While this is an open value, you may wish to use a boolean string value (@"0" or @"1") for this value, especially if using the predefined constant action names EPZ_PUSH_ACTION_NAME_RECEIVED or EPZ_PUSH_ACTION_NAME_OPENED, as defined in EPZConstants.
action
The action name to record for the event. While this is an open value, you may use the Constant values EPZ_PUSH_ACTION_NAME_RECEIVED and EPZ_PUSH_ACTION_NAME_OPENED, as defined in EPZConstants, as they provide a good base to normalize action names across your application.
callbackBlock
A block that is called upon completion of the fetch request. The block’s arguments are an NSDictionary of event data (populated if successful) and an NSError (nil unless unsuccessful).

Discussion
This method makes an asynchronous request to record an action for a specific push notification preference. When successful, the event data is passed in to the callback block as the "data" argument for convenience.

Since the block callback is used for both success and error events, it is advisable to implement a conditional check for the error object in your callback block, like in the code sample below. Note that the code sample below expands upon the code sample from the fetchAdditionalNotificationDataForPayloadID:callback: method above, and uses its callback block data to gather information for recording the action.

// AppDelegate.m
- (void) application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    // Check notification userInfo for remote payload ID and fetch additional notification data, if found.
    NSString *remotePayloadID = [[userInfo objectForKey:EPZ] objectForKey:EPZ_PUSH_KEY_PAYLOAD_ID];
    if (remotePayloadID) {
        [[EPZPushNotificationService sharedService] fetchAdditionalNotificationDataForPayloadID:remotePayloadId callback:^(NSDictionary *data, NSError *error) {
            if (error) {
                // Handle error as needed.
            } else {
                // Additional notification data successfully retrieved. Record "received" action on this notification.
                NSString *payloadIDFromData = [data objectForKey:EPZ_PUSH_KEY_PAYLOAD_ID];
                [[EPZPushNotificationService sharedService] recordActionForPushNotificationID:payloadIDFromData 
                                                                                    withValue:@"1" 
                                                                                    forAction:EPZ_PUSH_ACTION_NAME_RECEIVED 
                                                                                     callback:^(NSDictionary *data, NSError *error) {
                    if (error) {
                        // Handle error as needed.
                    } else {
                        // Action successfully recorded.
                    }
                }];
            }
        }];
    }
}


Note: The data object passed back in the callback block will have a structure like the code snippet below:

{
    action = "received";
    id = "10";
    remotePayloadId = "42";
    value = "1";
}

Declared In
EPZPushNotificationService.h

Personal tools