Skip to content

Push notifications integration

This reference article covers how to set up iOS push notifications for the Braze Swift SDK.

Push notifications allow you to send out notifications from your app when important events occur. You might send a push notification when you have new instant messages to deliver, breaking news alerts to send, or the latest episode of your user’s favorite TV show ready for them to download for offline viewing. Push notifications can also be silent, being used only to update your app’s interface or trigger background work.

Push notifications are great for sporadic but immediately important content, where the delay between background fetches might not be acceptable. Push notifications can also be much more efficient than background fetch, as your application only launches when necessary.

Push notifications are rate-limited, so don’t be afraid of sending as many as your application needs. iOS and the Apple Push Notification service (APNs) servers will control how often they are delivered, and you won’t get into trouble for sending too many. If your push notifications are throttled, they might be delayed until the next time the device sends a keep-alive packet or receives another notification.

Initial setup

Step 1: Upload your APNs certificate

Before you can send an iOS push notification using Braze, you must provide your .p8 push notification file provided by Apple. As described on the Apple developer documentation:

  1. In your Apple developer account, go to Certificates, Identifiers & Profiles.
  2. Under Keys, select All and click the add button (+) in the upper-right corner.
  3. Under Key Description, enter a unique name for the signing key.
  4. Under Key Services, select the Apple Push Notification service (APNs) checkbox, then click Continue. Click Confirm.
  5. Note the key ID. Click Download to generate and download the key. Make sure to save the downloaded file in a secure place, as you cannot download this more than once.
  6. In Braze, go to Settings > App Settings and upload the .p8 file under Apple Push Certificate. You can upload either your development or production push certificate. To test push notifications after your app is live in the App Store, its recommended to set up a separate workspace for the development version of your app.
  7. When prompted, enter your app’s bundle ID, key ID, and team ID, then click Save.

Step 2: Enable push capabilities

In Xcode, add the Push Notifications capability using the Signing & Capabilities pane to the main app target.

Automatic push integration

The Swift SDK provides a configuration-only approach to automate the processing of remote notifications received from Braze. This approach is the simplest way to integrate push notifications and is recommended for most customers.

To enable the automatic push integration, set the automation property of the push configuration to true:

1
2
let configuration = Braze.Configuration(apiKey: "{YOUR-BRAZE-API-KEY}", endpoint: "{YOUR-BRAZE-API-ENDPOINT}")
configuration.push.automation = true
1
2
BRZConfiguration *configuration = [[BRZConfiguration alloc] initWithApiKey:@"{YOUR-BRAZE-API-KEY}" endpoint:@"{YOUR-BRAZE-API-ENDPOINT}"];
configuration.push.automation = [[BRZConfigurationPushAutomation alloc] initEnablingAllAutomations:YES];

This instructs the SDK to:

  • Register your application for push notification on the system.
  • Request the push notification authorization/permission at initialization.
  • Dynamically provide implementations for the push notification related system delegate methods.

Overriding individual configurations

For more granular control, each automation step can be enabled or disabled individually:

1
2
3
// Enable all automations and disable the automatic notification authorization request at launch.
configuration.push.automation = true
configuration.push.automation.requestAuthorizationAtLaunch = false
1
2
3
// Enable all automations and disable the automatic notification authorization request at launch.
configuration.push.automation = [[BRZConfigurationPushAutomation alloc] initEnablingAllAutomations:YES];
configuration.push.automation.requestAuthorizationAtLaunch = NO;

See Braze.Configuration.Push.Automation for all available options and automation for more information on the automation behavior.

You can skip the next section and continue to deep linking if you are using the automatic push integration.

Manual push integration

Push notifications can also be integrated manually. This section describes the steps necessary for this integration.

Step 1: Register for push notifications with APNs

Include the appropriate code sample within your app’s application:didFinishLaunchingWithOptions: delegate method so that your users’ devices can register with APNs. Ensure that you call all push integration code in your application’s main thread.

Braze also provides default push categories for push action button support, which must be manually added to your push registration code. Refer to push action buttons for additional integration steps.

Add the following code to the application:didFinishLaunchingWithOptions: method of your app delegate.

1
2
3
4
5
6
7
8
9
10
11
application.registerForRemoteNotifications()
let center = UNUserNotificationCenter.current()
center.setNotificationCategories(Braze.Notifications.categories)
center.delegate = self
var options: UNAuthorizationOptions = [.alert, .sound, .badge]
if #available(iOS 12.0, *) {
  options = UNAuthorizationOptions(rawValue: options.rawValue | UNAuthorizationOptions.provisional.rawValue)
}
center.requestAuthorization(options: options) { granted, error in
  print("Notification authorization, granted: \(granted), error: \(String(describing: error))")
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
[application registerForRemoteNotifications];
UNUserNotificationCenter *center = UNUserNotificationCenter.currentNotificationCenter;
[center setNotificationCategories:BRZNotifications.categories];
center.delegate = self;
UNAuthorizationOptions options = UNAuthorizationOptionAlert | UNAuthorizationOptionSound | UNAuthorizationOptionBadge;
if (@available(iOS 12.0, *)) {
  options = options | UNAuthorizationOptionProvisional;
}
[center requestAuthorizationWithOptions:options
                      completionHandler:^(BOOL granted, NSError *_Nullable error) {
                        NSLog(@"Notification authorization, granted: %d, "
                              @"error: %@)",
                              granted, error);
}];

Step 2: Register push tokens with Braze

Once APNs registration is complete, pass the resulting deviceToken to Braze to enable for push notifications for the user.

Add the following code to your app’s application(_:didRegisterForRemoteNotificationsWithDeviceToken:) method:

1
AppDelegate.braze?.notifications.register(deviceToken: deviceToken)

Add the following code to your app’s application:didRegisterForRemoteNotificationsWithDeviceToken: method:

1
[AppDelegate.braze.notifications registerDeviceToken:deviceToken];

Step 3: Enable push handling

Next, pass the received push notifications along to Braze. This step is necessary for logging push analytics and link handling. Ensure that you call all push integration code in your application’s main thread.

Add the following code to your app’s application(_:didReceiveRemoteNotification:fetchCompletionHandler:) method:

1
2
3
4
5
6
7
if let braze = AppDelegate.braze, braze.notifications.handleBackgroundNotification(
  userInfo: userInfo,
  fetchCompletionHandler: completionHandler
) {
  return
}
completionHandler(.noData)

Next, add the following code to your app’s userNotificationCenter(_:didReceive:withCompletionHandler:) method:

1
2
3
4
5
6
7
if let braze = AppDelegate.braze, braze.notifications.handleUserNotification(
  response: response,
  withCompletionHandler: completionHandler
) {
  return
}
completionHandler()

Foreground push handling

To display a push notification while the app is in the foreground, implement userNotificationCenter(_:willPresent:withCompletionHandler:):

1
2
3
4
5
6
7
8
9
func userNotificationCenter(_ center: UNUserNotificationCenter,
                            willPresent notification: UNNotification,
                            withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
  if #available(iOS 14.0, *) {
    completionHandler([.list, .banner])
  } else {
    completionHandler([.alert])
  }
}

If the foreground notification is clicked, the push delegate userNotificationCenter(_:didReceive:withCompletionHandler:) will be called, and Braze will log a push click event.

Add the following code to your application’s application:didReceiveRemoteNotification:fetchCompletionHandler: method:

1
2
3
4
5
6
7
BOOL processedByBraze = AppDelegate.braze != nil && [AppDelegate.braze.notifications handleBackgroundNotificationWithUserInfo:userInfo
                                                                                                       fetchCompletionHandler:completionHandler];
if (processedByBraze) {
  return;
}

completionHandler(UIBackgroundFetchResultNoData);

Next, add the following code to your app’s (void)userNotificationCenter:didReceiveNotificationResponse:withCompletionHandler: method:

1
2
3
4
5
6
7
BOOL processedByBraze = AppDelegate.braze != nil && [AppDelegate.braze.notifications handleUserNotificationWithResponse:response
                                                                                                  withCompletionHandler:completionHandler];
if (processedByBraze) {
  return;
}

completionHandler();

Foreground push handling

To display a push notification while the app is in the foreground, implement userNotificationCenter:willPresentNotification:withCompletionHandler::

1
2
3
4
5
6
7
8
9
- (void)userNotificationCenter:(UNUserNotificationCenter *)center
       willPresentNotification:(UNNotification *)notification
         withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler {
  if (@available(iOS 14.0, *)) {
    completionHandler(UNNotificationPresentationOptionList | UNNotificationPresentationOptionBanner);
  } else {
    completionHandler(UNNotificationPresentationOptionAlert);
  }
}

If the foreground notification is clicked, the push delegate userNotificationCenter:didReceiveNotificationResponse:withCompletionHandler: will be called, and Braze will log a push click event.

Deep linking

Deep linking from a push into the app is automatically handled via our standard push integration documentation. If you’d like to learn more about how to add deep links to specific locations in your app, see our advanced use cases.

Subscribing to push notifications updates

To access the push notification payloads processed by Braze, use the Braze.Notifications.subscribeToUpdates(_:) method.

1
2
3
4
5
6
// This subscription is maintained through a Braze cancellable, which will observe for changes until the subscription is cancelled.
// You must keep a strong reference to the cancellable to keep the subscription active.
// The subscription is canceled either when the cancellable is deinitialized or when you call its `.cancel()` method.
let cancellable = AppDelegate.braze?.notifications.subscribeToUpdates { payload in
  print("Braze processed notification with title '\(payload.title)' and body '\(payload.body)'")
}
1
2
3
BRZCancellable *cancellable = [notifications subscribeToUpdatesWithInternalNotifications:NO update:^(BRZNotificationsPayload * _Nonnull payload) {
  NSLog(@"Braze processed notification with title '%@' and body '%@'", payload.title, payload.body);
}];

Testing

If you’d like to test in-app and push notifications via the command line, you can send a single notification through the terminal via CURL and the messaging API. You will need to replace the following fields with the correct values for your test case:

  • YOUR_API_KEY - available at Settings > API Keys.
  • YOUR_EXTERNAL_USER_ID - available on the Search Users page. See assigning user IDs for more information.
  • YOUR_KEY1 (optional)
  • YOUR_VALUE1 (optional)
1
2
3
4
5
6
7
8
9
10
11
curl -X POST -H "Content-Type: application/json" -H "Authorization: Bearer {YOUR_API_KEY}" -d '{
  "external_user_ids":["YOUR_EXTERNAL_USER_ID"],
  "messages": {
    "apple_push": {
      "alert":"Test push",
      "extra": {
        "YOUR_KEY1":"YOUR_VALUE1"
      }
    }
  }
}' https://rest.iad-01.braze.com/messages/send

The preceding example is for customers on the US-01 instance. If you are not on this instance, refer to our API documentation to see which endpoint to make requests to.

Push primers

Push primer campaigns encourage your users to enable push notifications on their device for your app. This can be done without SDK customization using our no code push primer.

HOW HELPFUL WAS THIS PAGE?
New Stuff!