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.

Step 1: Configure push notifications

Before you can send an iOS push notification using Braze, you must provide your push notification file or certificate from Apple. You may present either a .p8 file (recommended) or a .p12 certificate.

Using a .p12 certificate (legacy)

You may choose to use Apple’s older authentication scheme (.p12 SSL certificates). Unlike the .p8 solution, these certificates automatically expire every year and will require you to regenerate and re-upload them. Braze will send you email reminders as the certificate approaches expiration to help your notifications continue uninterrupted, but because this is a manual process, we recommend utilizing the .p8 authentication scheme instead. However, if you still wish to, you may configure and upload .p12 certificates as described in the following section:

Generate certificate signing request

  1. Navigate to the iOS Provisioning Portal.
  2. Select Identifiers in the sidebar.
  3. Select your application.
  4. If push notifications are not enabled, click Edit to update the app settings.
  5. Tick the Enable check box and click Configure to create a Production SSL Certificate
  6. Follow the instructions from the SSL certificate assistant. You should now see an “Enabled” status to indicate that push is enabled.
  7. You must update your provisioning profile for the app after you create your SSL certificates. A simple refresh in the organizer will accomplish this.

Export certificate

  1. Download the production push certificate you just created and open it with the Keychain Access application.
  2. In Keychain Access, click on My Certificates and locate your push certificate.
  3. Export it as a .p12 file and use a temporary, unsecure password (you will need this password when uploading your certificate to Braze).
  4. Navigate to Manage Settings > Settings in the dashboard and upload your production certificate under Apple Push Certificate.

You can upload either your development or production push certificates to the dashboard for your distribution provisioning profile apps, but you can only have one active at a time. If you wish to do repeated testing of push notifications once your app goes live in the App Store, we recommend setting up a separate workspace or app for the development version of your app.

Step 2: Enable push capabilities

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

Step 3: 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 4: 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 5: 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.

Step 6: 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.

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.

WAS THIS PAGE HELPFUL?
New Stuff!