iOS Push Notifications (APNs)
Send push notifications to iOS apps through Apple using a token-based .p8 key. One key works for all your apps and does not expire each year like push certificates do.
If you already use Firebase for iOS, you can send through FCM instead. Read the push notifications overview first for how the pieces fit together.
Before you start
Check you have everything on this list:
- Bento Chat on your plan. Push runs on Bento Chat, a $30 per month add-on.
- An approved Bento account.
- The administrator role in Bento, so you can open Push.
- An Apple Developer Program membership with access to Certificates, Identifiers & Profiles.
- Your app's bundle ID, for example
com.acme.app. - A backend that can call Bento's push API. See the backend example.
Bento has a setup guide that walks you through the same steps. Go to Marketing > Push > Apps and choose Set up push. The guide has five steps: Platform (pick iOS (Swift)), Create a key, Add credential, Connect your app, and Send a test.
Setup steps
- Create an APNs key in your Apple Developer account.
- Find your Team ID and bundle ID.
- Save the key in Bento.
- Add capabilities in Xcode.
- Request permission and register for notifications in your app.
- Send the device to your backend.
- Handle taps and buttons.
- Show images and buttons with a Notification Service Extension.
- Revoke on logout.
- Send a test.
Read Sandbox and production before step 3 if you test from Xcode.
Create an APNs key
Step 1 of 10.
- Go to developer.apple.com and sign in to your account.
- Open Certificates, Identifiers & Profiles, then Keys.
- Click + to create a key.
- Enter a name, such as
Bento push. - Tick Apple Push Notifications service (APNs) and click Configure.
- Set the environment to Sandbox & Production (recommended), then save the configuration.
- Click Continue, then Register.
- Click Download to save the
.p8file.
Apple lets you download the .p8 file only once, so store it somewhere safe, such as your password manager.
The key page shows the Key ID, a 10-character code of uppercase letters and digits.
Find your Team ID and bundle ID
Step 2 of 10.
- Team ID: shown at the top right of your developer account, or under Account > Membership details. It is 10 uppercase letters and digits.
- Bundle ID: in Certificates, Identifiers & Profiles > Identifiers, open your app. You can also find it in Xcode under your app target > General > Bundle Identifier.
While you have the identifier open, check that the Push Notifications capability is enabled for the App ID. Save the change if you had to turn it on.
Save the key in Bento
Step 3 of 10.
- In Bento, go to Marketing > Push > Apps and choose Set up push.
- On Platform, pick iOS (Swift).
- On Add credential, fill in:
- APNs key (.p8): the contents of the
.p8file, starting with-----BEGIN PRIVATE KEY----- - Key ID
- Team ID
- Bundle ID
- Environment: Production or Sandbox. Use Sandbox for development builds you install from Xcode.
- APNs key (.p8): the contents of the
- Save the credential. Bento checks the key when you save it and shows the problem to fix if something is wrong.
- On Connect your app, copy the Credential ID. Your backend sends it with every device registration.
Each app on Marketing > Push > Apps shows a status: Working, Not checked, or Not working.
You can also add keys without the guide. On Marketing > Push > Apps, choose Add keys yourself or Add app, then fill in Push service (pick Apple (APNs)), Name, iOS bundle ID, Environment, Key ID, Team ID, and Private key.
Sandbox and production
Apple issues different device tokens depending on how the app was installed:
| Build | Environment |
|---|---|
| Debug builds run from Xcode | sandbox |
| TestFlight, App Store, and Ad Hoc builds | production |
A token only works with a credential for the same environment. If you test from Xcode and also ship to TestFlight or the App Store, save two credentials with the same key: one sandbox and one production. Each bundle ID can have one credential per environment.
Your app tells your backend which environment the build uses, so the backend can pick the matching credential ID. The apnsEnvironment property in Send the device to your backend uses #if DEBUG for this. That works when you run the Debug configuration from Xcode and archive the Release configuration. Adjust it if you archive other configurations.
Add capabilities in Xcode
Step 4 of 10.
- Select your app target, then open Signing & Capabilities.
- Click + Capability and add Push Notifications. This adds the
aps-environmententitlement. - If you need to handle notifications in the background, click + Capability again, add Background Modes, and tick Remote notifications.
Request permission and register
Step 5 of 10.
This AppDelegate asks for permission, registers with APNs, and sends the token to your backend. In a SwiftUI app, attach it with @UIApplicationDelegateAdaptor(AppDelegate.self).
import UIKit
import UserNotifications
class AppDelegate: NSObject, UIApplicationDelegate, UNUserNotificationCenterDelegate {
func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil
) -> Bool {
let center = UNUserNotificationCenter.current()
center.delegate = self
center.setNotificationCategories([BentoPush.actionsCategory])
center.requestAuthorization(options: [.alert, .badge, .sound]) { _, _ in
DispatchQueue.main.async {
UIApplication.shared.registerForRemoteNotifications()
}
}
return true
}
func application(
_ application: UIApplication,
didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data
) {
let token = deviceToken.map { String(format: "%02x", $0) }.joined()
BentoPush.register(token: token)
}
func application(
_ application: UIApplication,
didFailToRegisterForRemoteNotificationsWithError error: Error
) {
print("APNs registration failed: \(error)")
}
}The app registers for remote notifications on every launch, even if the person declined. That keeps the token current, and the backend still learns the permission, so Bento can start sending if they turn notifications on later in Settings.
Send the device to your backend
Step 6 of 10.
The app generates an installation ID once and keeps it. Your backend adds the subscriber's email, the Credential ID, and your Bento keys, then calls Bento. See the backend example.
import UIKit
import UserNotifications
enum BentoPush {
static let actionsCategory = UNNotificationCategory(
identifier: "BENTO_ACTIONS", actions: [], intentIdentifiers: [], options: []
)
static var installationID: String {
let key = "push_installation_id"
if let existing = UserDefaults.standard.string(forKey: key) { return existing }
let id = UUID().uuidString
UserDefaults.standard.set(id, forKey: key)
return id
}
static var apnsEnvironment: String {
#if DEBUG
return "sandbox"
#else
return "production"
#endif
}
static func register(token: String) {
UNUserNotificationCenter.current().getNotificationSettings { settings in
MyBackend.send("POST", "/me/push-device", json: [
"installation_id": installationID,
"token": token,
"platform": "ios",
"apns_environment": apnsEnvironment,
"permission": permission(settings.authorizationStatus),
"app_version": Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "",
"os_version": UIDevice.current.systemVersion,
"locale": Locale.current.identifier,
"timezone": TimeZone.current.identifier,
])
}
}
static func unregister() {
MyBackend.send("DELETE", "/me/push-device?installation_id=\(installationID)&platform=ios&apns_environment=\(apnsEnvironment)")
}
static func reportOpen(_ openToken: String) {
MyBackend.send("POST", "/me/push-opens", json: ["open_token": openToken])
}
private static func permission(_ status: UNAuthorizationStatus) -> String {
switch status {
case .authorized: return "granted"
case .provisional: return "provisional"
case .denied: return "denied"
case .notDetermined: return "not_determined"
default: return "unknown"
}
}
}
enum MyBackend {
static func send(_ method: String, _ path: String, json: [String: Any]? = nil) {
var request = URLRequest(url: URL(string: "https://api.example.com\(path)")!)
request.httpMethod = method
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
// Add your app's login session header here.
if let json { request.httpBody = try? JSONSerialization.data(withJSONObject: json) }
URLSession.shared.dataTask(with: request).resume()
}
}Store the installation ID in the Keychain instead of UserDefaults if you want it to survive a reinstall.
Handle taps and buttons
Step 7 of 10.
When someone taps a notification or one of its buttons, report the open and follow the link. Add these methods to your AppDelegate:
struct BentoAction: Decodable {
let id: String
let title: String
let url: String?
}
func bentoActions(from userInfo: [AnyHashable: Any]) -> [BentoAction] {
guard let json = userInfo["bento_actions"] as? String,
let data = json.data(using: .utf8) else { return [] }
return (try? JSONDecoder().decode([BentoAction].self, from: data)) ?? []
}
extension AppDelegate {
func userNotificationCenter(
_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void
) {
completionHandler([.banner, .list, .sound])
}
func userNotificationCenter(
_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: @escaping () -> Void
) {
let userInfo = response.notification.request.content.userInfo
if let openToken = userInfo["bento_open_token"] as? String {
BentoPush.reportOpen(openToken)
}
var link = userInfo["bento_url"] as? String
if response.actionIdentifier != UNNotificationDefaultActionIdentifier,
let action = bentoActions(from: userInfo).first(where: { $0.id == response.actionIdentifier }) {
link = action.url
}
if let link, let url = URL(string: link) {
UIApplication.shared.open(url)
}
completionHandler()
}
}willPresent shows notifications that arrive while the app is open. Without it, iOS hides them.
Show images and buttons
Step 8 of 10.
iOS only shows buttons for a notification category the app has registered. When a campaign has buttons and no custom category, Bento sends the category BENTO_ACTIONS. The AppDelegate registers that category at launch, but button titles change from campaign to campaign, so a Notification Service Extension fills them in before the notification appears. The extension also downloads bento_image_url and attaches the image. Bento marks the notification as mutable when it has an image or buttons, so the extension runs for those notifications.
To add the extension, choose File > New > Target > Notification Service Extension in Xcode, then replace NotificationService.swift:
import UserNotifications
struct BentoAction: Decodable {
let id: String
let title: String
}
class NotificationService: UNNotificationServiceExtension {
private var contentHandler: ((UNNotificationContent) -> Void)?
private var content: UNMutableNotificationContent?
override func didReceive(
_ request: UNNotificationRequest,
withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void
) {
self.contentHandler = contentHandler
guard let content = request.content.mutableCopy() as? UNMutableNotificationContent else {
contentHandler(request.content)
return
}
self.content = content
registerActions(from: content.userInfo) {
self.attachImage(to: content) {
contentHandler(content)
}
}
}
override func serviceExtensionTimeWillExpire() {
if let contentHandler, let content {
contentHandler(content)
}
}
private func registerActions(from userInfo: [AnyHashable: Any], completion: @escaping () -> Void) {
guard let json = userInfo["bento_actions"] as? String,
let data = json.data(using: .utf8),
let actions = try? JSONDecoder().decode([BentoAction].self, from: data),
!actions.isEmpty else {
completion()
return
}
let category = UNNotificationCategory(
identifier: "BENTO_ACTIONS",
actions: actions.map { UNNotificationAction(identifier: $0.id, title: $0.title, options: [.foreground]) },
intentIdentifiers: [],
options: []
)
let center = UNUserNotificationCenter.current()
center.getNotificationCategories { existing in
let others = existing.filter { $0.identifier != "BENTO_ACTIONS" }
center.setNotificationCategories(others.union([category]))
completion()
}
}
private func attachImage(to content: UNMutableNotificationContent, completion: @escaping () -> Void) {
guard let link = content.userInfo["bento_image_url"] as? String,
let url = URL(string: link) else {
completion()
return
}
URLSession.shared.downloadTask(with: url) { location, _, _ in
defer { completion() }
guard let location else { return }
let fileExtension = url.pathExtension.isEmpty ? "jpg" : url.pathExtension
let file = FileManager.default.temporaryDirectory
.appendingPathComponent(UUID().uuidString)
.appendingPathExtension(fileExtension)
try? FileManager.default.moveItem(at: location, to: file)
if let attachment = try? UNNotificationAttachment(identifier: "image", url: file) {
content.attachments = [attachment]
}
}.resume()
}
}The .foreground option opens your app when someone taps a button, so the tap handler can report the open and follow the button's link.
Revoke on logout
Step 9 of 10.
Call this before you clear the login session, so your backend still knows who the device belongs to:
BentoPush.unregister()Send a test
Step 10 of 10.
- Run your app on a real device, allow notifications, and sign in as a subscriber so your backend registers the device.
- Send a test in either of these places:
- The Send a test step at the end of the setup guide in Marketing > Push > Apps.
- Send a test on any push campaign.
- Enter the subscriber email the device was registered with.
If the notification does not arrive, check that the credential environment matches the build. A build you install from Xcode needs a Sandbox credential. Then see Troubleshooting.
Troubleshooting
These are the most common problems and how to fix them:
| Problem | Cause | Fix |
|---|---|---|
BadDeviceToken | The token came from the other environment, such as a sandbox token sent with a production credential. Or the token is not a valid hex string. | Match the credential to the build (see Sandbox and production). Send deviceToken converted to a hex string. |
DeviceTokenNotForTopic | The credential's bundle ID does not match the app that produced the token. | Update the bundle ID on the credential in Bento. |
Unregistered | The app was uninstalled or the token expired. | Nothing to do. Bento stops sending to that device, and the app registers a fresh token on its next launch. |
| Pushes to Xcode builds never arrive | Debug builds from Xcode get sandbox tokens. | Save a sandbox credential and send its ID for Debug builds. |
no valid aps-environment entitlement string found | The app is missing the push entitlement. | Add the Push Notifications capability in Xcode, enable it on the App ID, and regenerate the provisioning profile. |
422 "Check the subscriber's email address or uuid." | The visitor_id isn't a subscriber on this site, or the email or uuid isn't valid. | Register with the subscriber's email or uuid. Bento adds them if they're new. |