Push Notifications
Airship’s SDK provides a simple interface for managing push notifications within your iOS application.
Push
Push is available in the AirshipCore module and subspec.
Importing the module
For CocoaPods, import using:
import AirshipKit
@import AirshipKit;
For everything else, use:
import AirshipCore
@import AirshipCore;
Enabling User Notifications
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.
Airship.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.
Airship.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.
Airship.push.notificationOptions = [.alert, .badge, .sound, .provisional]
Airship.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. 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
.
Airship.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.
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
UPushNotificationDelegate
on PushAirship.push.pushNotificationDelegate = customPushDelegate
UAirship.push.pushNotificationDelegate = customPushDelegate;
class SamplePushHandler: NSObject, PushNotificationDelegate {
public func receivedBackgroundNotification(_ userInfo: [AnyHashable : Any], completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
// Background content-available notification
completionHandler(.noData)
}
public func receivedForegroundNotification(_ userInfo: [AnyHashable : Any], completionHandler: @escaping () -> Void) {
// Foreground notification
completionHandler()
}
public func receivedNotificationResponse(_ notificationResponse: UNNotificationResponse, completionHandler: @escaping () -> Void) {
// Notification response
completionHandler()
}
public func extend(_ options: UNNotificationPresentationOptions, notification: UNNotification) -> UNNotificationPresentationOptions {
return [.alert, .sound]
}
}
@implementation SamplePushHandler
-(void)receivedBackgroundNotification:(UNNotificationContent *)notificationContent completionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
// Background content-available notification
completionHandler(UIBackgroundFetchResultNoData);
}
-(void)receivedForegroundNotification:(UNNotificationContent *)notificationContent completionHandler:(void (^)(void))completionHandler {
// Foreground notification
completionHandler();
}
-(void)receivedNotificationResponse:(UNNotificationResponse *)notificationResponse completionHandler:(void (^)(void))completionHandler {
// Notification response
completionHandler();
}
- (UNNotificationPresentationOptions)extendPresentationOptions:(UNNotificationPresentationOptions)options notification:(UNNotification *)notification {
// 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.
Airship.push.badgeNumber = 20
UAirship.push.badgeNumber = 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
.
Airship.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.
Airship.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
Airship.push.setQuietTimeStartHour(19, startMinute: 30, endHour: 7, endMinute: 30)
// Enable quiet time
Airship.push.quietTimeEnabled = true
// Update registration
Airship.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)
In order to define a custom Interactive Notification type, you must register a new category.
Airship reserves category IDs prefixed with “ua_
”. Any custom categories
with that prefix will be dropped.
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 or newer.
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
.
// Define an action for the category
let categoryAction = UNNotificationAction(identifier: "category_action",
title: "Action!",
options: [.authenticationRequired, .foreground, .destructive])
// Define the category
let category = UNNotificationCategory(identifier: "custom_category",
actions: [categoryAction],
intentIdentifiers: [],
hiddenPreviewsBodyPlaceholder: "Sensitive Content Hidden",
options: [])
// Set the custom categories
Airship.push.customCategories = [category]
// Update registration
Airship.push.updateRegistration()
// Define an action for the category
UNNotificationAction *categoryAction = [UNNotificationAction actionWithIdentifier: @"category_action"
title:@"Action!"
options:(UNNotificationActionOptionForeground |
UNNotificationActionOptionDestructive |
UNNotificationActionOptionAuthenticationRequired)];
// Define the category
UNNotificationCategory *category = [UNNotificationCategory 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 .
Silent Notifications
Silent notifications on iOS are notifications with no alert, sound, or badge content. These are typically used to briefly wake the app from a background state to perform processing tasks or fetch remote content. To send a silent notification in the API, set the content_available
property to true
in the iOS override object.
If the push is handled in the background, it is the app’s responsibility to call the completion handler in a timely fashion. The typical background processing time granted to the app by iOS is around 30 seconds.
Pushes sent with the content_available
property do not have guaranteed delivery. Factors affecting delivery include battery life, whether the device is connected to WiFi, and the number of content_available
pushes sent within a recent time period. These metrics are determined solely by iOS and APNs. Therefore, this feature is best used for supplementing the regular behavior of the app rather than providing critical functionality. For instance, an app could use a silent push to pre-fetch new data ahead of time in order to reduce load times when the app is later launched by the user.
iOS-Specific Payloads
iOS has several features not present in other platforms. These can be specified
in the iOS override in the notification
object.
Categories