Push Notifications

Airship's SDK provides a simple interface for managing push notifications within your iOS application.

Enabling User Notifications

 Note

Enabling userPushNotificationsEnabled will prompt the user for permission to send notifications. To increase the likelihood that the user will accept, you should avoid prompting the user for permission immediately, and instead wait for a more appropriate time in the app.

The Airship SDK makes a distinction between "user notifications", which can be seen by the user, and other forms of push that allow you to send data to your app silently, or in the background. Enabling or disabling user notifications is a preference often best left up to the user, so by default, user notifications are disabled.

Enable user notifications
UAirship.push().userPushNotificationsEnabled = true
[UAirship push].userPushNotificationsEnabled = YES;

Notification Options

By default the Airship SDK will request Alert, Badge, and Sound notification options for remote notifications. This can be configured by setting different types of notificationOptions on the UAPush instance.

Update remote notification options
UAirship.push().notificationOptions = [.alert, .badge, .sound]
[UAirship push].notificationOptions = (UANotificationOptionAlert | UANotificationOptionBadge | UANotificationOptionSound);

Provisional authorization

Starting in iOS 12, apps can request provisional authorization along with the usual notification options. When requesting provisional authorization apps do not need to prompt the user for permission initially, and notifications will be delivered in a non-interruptive manner to the Notification Center until the user explicitly chooses to keep delivering messages either prominently or quietly. Because this form of authorization requires no initial user prompt, it is acceptable to programmatically enable user notifications, which is still required for any visible notification delivery.

Requesting provisional authorization
UAirship.push().notificationOptions = [.alert, .badge, .sound, .provisional]
UAirship.push().userPushNotificationsEnabled = true
[UAirship push].notificationOptions = (UANotificationOptionAlert | UANotificationOptionBadge | UANotificationOptionSound | UANotificationOptionProvisional);
[UAirship push].userPushNotificationsEnabled = YES;

Foreground Presentation Options

The SDK provides support for foreground presentation options that were introduced in iOS 10. The three UNNotificationPresentationOptions constants are badge, sound, and alert. These constants specify how to present a notification when the application receives a remote notification in the foreground. You can set default presentation options that will be applied to all remote-notifications, and you can also provide options per notification by providing a UAPushNotificationDelegate .

Setting default presentation options
UAirship.push().defaultPresentationOptions = [.alert, .badge, .sound]
[UAirship push].defaultPresentationOptions = (UNNotificationPresentationOptionAlert |
                                              UNNotificationPresentationOptionBadge |
                                              UNNotificationPresentationOptionSound);

Handling Notifications

iOS handles push notifications received outside the application, but if a notification is received while the app is active, it's up to the application developer to handle it. Versions prior to iOS 10 require the application developer to manually create an alert view and populate it with the notification contents. In iOS 10 and above, the application developer has the additional option of using a system-generated alert view. A system-generated alert view is presented if the alert type is included in the UNNotificationPresentationOptions set on UAPush's defaultPresentationOptions property. These presentation options can be configured on a notification by notification basis by implementing the UAPushNotificationDelegate protocol's presentationOptions callback and returning the desired presentation options.

The sample UI includes a complete implementation of the UAPushNotificationDelegate protocol that handles alerts, sounds, and badges. However, if you wish to customize this behavior, you can provide your own implementation.

Set the UAPushNotificationDelegate on UAPush
UAirship.push().pushNotificationDelegate = customPushDelegate
[UAirship push].pushNotificationDelegate = customPushDelegate;
Sample UAPushNotificationDelegate implementation
class SamplePushHandler: NSObject, UAPushNotificationDelegate {

    func receivedBackgroundNotification(_ notificationContent: UANotificationContent, completionHandler: @escaping (UIBackgroundFetchResult) -> Swift.Void) {
        // Background content-available notification
        completionHandler(.noData)
    }

    func receivedForegroundNotification(_ notificationContent: UANotificationContent, completionHandler: @escaping () -> Swift.Void) {
        // Foreground notification
        completionHandler()
    }

    func receivedNotificationResponse(_ notificationResponse: UANotificationResponse, completionHandler: @escaping () -> Void) {
        // Notification response
        completionHandler()
    }

    func presentationOptions(for notification: UNNotification) -> UNNotificationPresentationOptions {
        return [.alert, .sound]
    }
}
@implementation PushHandler

    -(void)receivedBackgroundNotification:(UANotificationContent *)notificationContent completionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
        // Background content-available notification
        completionHandler(UIBackgroundFetchResultNoData);
    }

    -(void)receivedForegroundNotification:(UANotificationContent *)notificationContent completionHandler:(void (^)())completionHandler {
        // Foreground notification
        completionHandler();
    }

    -(void)receivedNotificationResponse:(UANotificationResponse *)notificationResponse completionHandler:(void (^)())completionHandler {
        // Notification response
        completionHandler();
    }

    - (UNNotificationPresentationOptions)presentationOptionsForNotification:(UNNotification *)notification {
        // iOS 10 foreground presentation options
        return UNNotificationPresentationOptionAlert | UNNotificationPresentationOptionSound;
    }
@end

Badges

You can set (or reset) the badge number within your application by setting the badge number on the UAPush instance.

Setting the badge value
UAirship.push().setBadgeNumber(20)
[[UAirship push] setBadgeNumber:20];

A typical application will reset the badge any time a user starts the app or resumes it from the background. This can be done by making UAPush resetBadge calls from application:didFinishLaunchingWithOptions: and applicationDidBecomeActive.

Reset the badge
UAirship.push().resetBadge()
[[UAirship push] resetBadge];

Additionally, Airship support an auto-badge feature. This allows incrementing the badge from a push instead of setting the exact value for the badge. When using auto-badge, make sure to only modify the badge value through Airship methods to ensure the value keeps in sync.

Enabling auto-badge
UAirship.push().autobadgeEnabled = true
[UAirship push].autobadgeEnabled = YES;

Quiet Time

Quiet time disables notification sounds during a set time frame by removing the sound APNs option before sending the notification to the device.

// Set the quiet time from 7:30pm - 7:30am
UAirship.push().setQuietTimeStartHour(19, startMinute: 30, endHour: 7, endMinute: 30)

// Enable quiet time
UAirship.push().isQuietTimeEnabled = true

// Update registration
UAirship.push().updateRegistration()
// Set the quiet time from 7:30pm - 7:30am
[[UAirship push] setQuietTimeStartHour:19 startMinute:30 endHour:7 endMinute:30];

// Enable quiet time
[UAirship push].quietTimeEnabled = YES;

// Update registration
[[UAirship push] updateRegistration];

Interactive Notifications

Airship provides a set of standard Interactive Notification types (See: Built-In Interactive Notification Types). It is the type that determines which buttons and corresponding labels will be available when you send a push. See the next section for where to specify that in the push payload. You control what happens when you send the push separately, by tying each button ID to a specific action.

Custom Interactive Notification Types (Categories)

 Note

Airship reserves category IDs prefixed with "ua_". Any custom categories with that prefix will be dropped.

In order to define a custom Interactive Notification type, you must register a new category.

You can use the hiddenPreviewsBodyPlaceholder argument to specify placeholder text which will be shown instead of the push notification's body when the user has disabled notification previews for the app in iOS 11.

Custom categories are supported by setting the set of categories on UAPush customCategories .

Categories can be set after takeOff. Any modifications to the user notification categories will require an update to the registration settings by calling UAPush updateRegistration .

Setting Custom Categories
// Define an action for the category
let categoryAction = UANotificationAction(identifier: "category_action",
                                               title: "Action!",
                                             options: [.authenticationRequired, .foreground, .destructive])

// Define the category
let category = UANotificationCategory(identifier: "custom_category",
                                         actions: [categoryAction],
                               intentIdentifiers: [],
                   hiddenPreviewsBodyPlaceholder: "Sensitive Content Hidden",
                                         options: [])

// Set the custom categories
UAirship.push().customCategories = [category]

// Update registration
UAirship.push().updateRegistration()
// Define an action for the category
UANotificationAction *categoryAction = [UANotificationAction actionWithIdentifier: @"category_action"
                                                                            title:@"Action!"
                                                                          options:(UNNotificationActionOptionForeground |
                                                                                  UNNotificationActionOptionDestructive |
                                                                                  UNNotificationActionOptionAuthenticationRequired)];

// Define the category
UANotificationCategory *category = [UANotificationCategory categoryWithIdentifier:@"custom_category"
                                                                          actions:@[categoryAction]
                                                                intentIdentifiers:@[]
                                                                          options:UNNotificationCategoryOptionNone];

// Set the custom categories
[UAirship push].customCategories = [NSSet setWithArray:@[category]];

// Update registration
[[UAirship push] updateRegistration];

User Notification Action Callbacks

Custom-defined Interactive Notification types can either make use of Airship's pre-defined actions, or you can write new custom action code. Callbacks are also provided through the UAPushNotificationDelegate .

iOS-Specific Payloads

iOS has several features not present in other platforms. These can be specified in the iOS override in the notification object.