Push notifications
iOS SDK v1.4.0 — Push notifications
The SDK has no push framework dependency of its own — it never calls
registerForRemoteNotifications, never receives a push, and doesn't present
a notification for you. What it does provide is the two hooks that connect
your APNs integration to Optima: registering the device's token so
campaigns can target it, and recording that a delivered push was opened. You
still write your own UNUserNotificationCenterDelegate.
APNs setup recipe
Request authorization and register the normal way — none of that is part of this SDK. Then wire the two callbacks:
import UserNotifications
import OptimaSDK
// AppDelegate
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
Optima.initialize(try! OptimaConfig(key: "oek_shop_a1b2c3", endpoint: "https://edge.shop.example"))
UNUserNotificationCenter.current().delegate = self
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { _, _ in
DispatchQueue.main.async { application.registerForRemoteNotifications() }
}
return true
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
Optima.shared.push.setToken(deviceToken)
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
// Your own error handling — the SDK has nothing to do here since there's no token to set.
}push.setToken(_ deviceToken: Data?) hex-encodes the token, stores it
(_optima_push_token), and — unless the edge has already accepted exactly
this token (_optima_push_synced) — calls identify(["push_token_apns": token])
to attach it to the device's current profile. An identify that could not
reach the edge (offline, 5xx) is retried at the next launch and on every
foreground until it gets an answer. A 4xx (e.g. identify disabled for the
SDK key) is final for that token — it is not retried until the token changes
or reset() runs. A 200 whose push_token_apns the edge dropped (the key is
missing from identify_allowed_keys) also counts as delivered: after fixing
the allowlist, call reset() or wait for a token change. Call it
from didRegisterForRemoteNotificationsWithDeviceToken every time; it's a
no-op once the token is synced, so there's no harm calling it unconditionally
on every launch too.
Reading and displaying the payload
extension AppDelegate: UNUserNotificationCenterDelegate {
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler([.banner, .sound, .badge]) // foreground presentation — your own choice
}
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
let userInfo = response.notification.request.content.userInfo
Optima.shared.push.trackOpen(userInfo)
if let push = Optima.shared.push.parse(userInfo) {
let tapped = push.buttons.first { $0.id == response.actionIdentifier }
route(deepLink: tapped?.deepLink ?? push.deepLink)
}
completionHandler()
}
}push.parse(_ userInfo: [AnyHashable: Any]) reads the reserved data keys the
deliverer sends — deep_link, buttons (a JSON array, already parsed into
[PushButton]), optima_open, image_url — and returns OptimaPush(deepLink: buttons:data:openToken:), where data is every other key (your own custom
payload data, with the reserved keys filtered out). It returns nil if none
of the reserved keys are present at all — a signal that this message wasn't
built by Optima's delivery pipeline, so you can fall through to whatever else
handles your other push sources. push.parse reads straight from the
notification's userInfo (the raw APNs payload as UNUserNotificationCenter
hands it to you) — there's no separate Bundle/Data overload to reach for,
unlike the Android SDK's Bundle vs. Map<String, String> split, since a
UNNotification's userInfo is already the one shape to read.
UNNotificationCategory for action buttons
Unlike Android (where push.parse's buttons list is just data you turn
into NotificationCompat.Actions at display time), iOS notification
action buttons must come from an app-registered UNNotificationCategory —
APNs itself has no way to attach ad-hoc buttons to a single payload. Register
a fixed set of categories up front (e.g. in application(_:didFinishLaunching WithOptions:)), and have your send-side templates reference one of those
category identifiers rather than expecting arbitrary per-send buttons:
let viewAction = UNNotificationAction(identifier: "VIEW", title: "View", options: [.foreground])
let dismissAction = UNNotificationAction(identifier: "DISMISS", title: "Dismiss", options: [.destructive])
let category = UNNotificationCategory(identifier: "optima_campaign", actions: [viewAction, dismissAction], intentIdentifiers: [], options: [])
UNUserNotificationCenter.current().setNotificationCategories([category])push.parse(_:).buttons still tells you what the campaign wants to offer
(useful for building your UNNotificationCategory set from what your
templates actually use, or for driving a custom in-app banner instead of a
system notification), but it cannot make the system tray show buttons it
wasn't told about ahead of time via content.categoryIdentifier on the
UNMutableNotificationContent/APNs payload — see Apple's Notification
Service Extension docs for the exact category-to-payload wiring; that step
happens entirely in your own app, outside this SDK.
Images: a Notification Service Extension
APNs delivers image_url as a plain data key — iOS does not download and
attach a remote image to a push notification on its own. Displaying
image_url requires your own Notification Service Extension (a small
additional app extension target) that intercepts the notification before
presentation, downloads the image, and attaches it as a
UNNotificationAttachment:
// NotificationService.swift, in the extension target
override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
guard let content = (request.content.mutableCopy() as? UNMutableNotificationContent),
let urlString = content.userInfo["image_url"] as? String, let url = URL(string: urlString) else {
contentHandler(request.content); return
}
URLSession.shared.downloadTask(with: url) { location, _, _ in
defer { contentHandler(content) }
guard let location else { return }
let dest = location.appendingPathExtension(url.pathExtension.isEmpty ? "jpg" : url.pathExtension)
try? FileManager.default.moveItem(at: location, to: dest)
if let attachment = try? UNNotificationAttachment(identifier: "image", url: dest) { content.attachments = [attachment] }
}.resume()
}This is standard Apple plumbing with nothing Optima-specific about it beyond
reading image_url out of userInfo — the SDK does not (and cannot, from
the app's main target alone) ship this extension for you, since it must live
in its own extension target with its own bundle id and code signing.
push.trackOpen
Call it from UNUserNotificationCenterDelegate.userNotificationCenter(_:didReceive:withCompletionHandler:)
(shown above) — that delegate method fires whether the app was foregrounded,
backgrounded, or launched cold by the notification tap, which covers every
case trackOpen needs to see. trackOpen(_ userInfo:) looks for
optima_open; if present and non-blank, it fires GET /edge/v1/o/{token}
fire-and-forget (a 5-attempt backoff ladder, failures logged at debug only —
a missed open record never surfaces as an app-visible error) and returns
true. If optima_open is absent, it does nothing and returns false —
safe to call unconditionally on every notification response, including one
from a non-Optima push source.
What the backend needs
Three prerequisites, all covered in the operator-facing sections of
FEATURES.md/TASK.md in the main optima repo:
EMAIL_TRACK_KEYmust be configured — the same key the email open pixel uses. Push opens are sealed with the identicalinternal/emailtrackmechanism, just taggedchannel: "push"instead of the email pixel's implicit channel.- Open tracking must be turned on for the push template (or the
instance-wide
email_open_trackingdefault, if the template doesn't override it) — the same switch email templates use, not a separate mobile-specific one. If it's off, the send simply never mints anoptima_openkey,push.parsereturnsopenToken == nil, andtrackOpencorrectly does nothing — there is no error state here, just "nothing to track." push_token_apnsmust be an allowlisted identifier in the tenant'sidentify_allowed_keys— otherwisepush.setToken'sidentify(...)call succeeds but the server drops the key (visible in the.identifyevent'sdroppedlist, and, more importantly, in a campaign never actually reaching the device because the token was never attached).
optima_open is a reserved data key — pushReservedDataKeys in the backend
rejects any attempt by a template author to set it themselves, so it's
always the delivery pipeline's own minted token, never something a
campaign's custom data payload could spoof or collide with.
reset() and the push token
reset() deliberately preserves _optima_push_token and, as one of its
final steps, re-sends it via identify(["push_token_apns": token]) under the
new device id (Push.onReset()) — because the physical device (and its
APNs registration) hasn't changed, only the person using the app has, and
pushes should keep reaching this device under whatever profile it resolves
to next.
If the outgoing user should not keep receiving pushes meant for this
device once a new person logs in — the common case for a genuinely
shared/kiosk device, less so for "my personal phone, I logged out of one
account and into another" — call push.setToken(hex: nil) before calling
reset(). Passing nil forgets the token locally without notifying the
server, so reset()'s re-attach step finds nothing to re-send:
func logout() {
Optima.shared.push.setToken(hex: nil)
Optima.shared.reset()
// Once a fresh token arrives via didRegisterForRemoteNotificationsWithDeviceToken (iOS
// re-delivers the current token on the next registerForRemoteNotifications() call, or on
// the next app start), call setToken(_:) again to re-attach it.
}