iOS SDK
Integrate ComRaid push on iOS with the Swift Package ComRaid — Subscription register, Login, Logout, Contact opt-in/out, remote display helpers, Notification Service Extension images, durable delivery ACKs, and local schedules/timers.
Package product/module: ComRaid. CocoaPods: pod 'ComRaid'. Vocabulary:
Endpoint / Subscription, external_user_id, Identity verification JWT
(login(externalUserId:jwt:)). Server-side sends use Message /
Notification (push-facing name), Campaign, Single send, Broadcast, and
Multi-send (/campaigns). Delivery outcomes: sent, delivered, opened, skipped,
failed. Message statuses: scheduled, preparing, processing, completed, failed,
cancelled.
Canonical method reference lives on this page. The package README stays at parity — see the comraid-ios README.
Install
Swift Package Manager — add the package dependency and import ComRaid:
import ComRaidCocoaPods:
pod 'ComRaid'Configure APNs (or FCM-for-iOS) credentials under Push → Push settings → Platforms. Related: Push providers, Migrate from OneSignal, Notifications.
Getting started
Configure early with a publishable App ID and APNs environment, then run the identity loop:
await ComRaid.shared.configure(
.init(
appId: "cr_app_your_id",
// apiBaseURL: URL(string: "http://localhost:8080")!, // optional; default https://api.comraid.io
apnsEnvironment: .sandbox // or .production
)
)
let granted = try await ComRaid.shared.requestPermission()
// In AppDelegate:
func application(
_ application: UIApplication,
didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data
) {
Task {
await ComRaid.shared.setAPNsDeviceToken(deviceToken)
try? await ComRaid.shared.register()
}
}
try await ComRaid.shared.login(externalUserId: "user_123")
try await ComRaid.shared.login(externalUserId: "user_123", jwt: jwtFromYourBackend)
try await ComRaid.shared.logout()
try await ComRaid.shared.optOut() // Contact Opted out of the push Channel (all Subscriptions)
try await ComRaid.shared.optIn()Logout makes the Subscription Inactive and clears its credential; the SDK
clears Keychain identity and registers a fresh Subscription afterward. Opted
out is Contact × Channel. Forward APNs tokens with setAPNsDeviceToken — when
a Subscription credential already exists, the SDK calls /token automatically
(preserves Subscription identity). Wire field is external_user_id.
Never embed cr_sk_... in the app. Use cr_app_... from Push → Push settings →
Platforms. See Authentication and
API Reference.
Method reference
Depth B: signature, purpose, parameters, and return type. Examples are clustered per lifecycle group — not one snippet per method.
Configure
configure(_:)
func configure(_ configuration: ComRaidConfiguration) throwsPersists App ID / API base / APNs environment, sets up Keychain Subscription
storage (id, credential, External user ID), restores a logged-in External user
ID when present, and starts ACK flush. Throws
ComRaidError.invalidConfiguration when appId is blank (does not crash).
| Parameter | Type | Description |
|---|---|---|
configuration | ComRaidConfiguration | appId (cr_app_…), optional apiBaseURL (default https://api.comraid.io), required apnsEnvironment, optional storageSuiteName, optional displayForegroundNotifications (default true) |
Returns: Void
setAPNsDeviceToken(_:)
func setAPNsDeviceToken(_ tokenData: Data) asyncStores the APNs device token from
application(_:didRegisterForRemoteNotificationsWithDeviceToken:). Notifies
addTokenRefreshListener subscribers. When a Subscription credential already
exists, also calls /token (same path as onPushTokenRefresh).
| Parameter | Type | Description |
|---|---|---|
tokenData | Data | Raw APNs device token |
Returns: Void
getToken()
func getToken() async throws -> StringProvider push token (APNs hex). Not a ComRaid Endpoint / Subscription id.
| Parameter | Type | Description |
|---|---|---|
| — | — | — |
Returns: String — APNs device token hex
getInitialNotification()
func getInitialNotification() -> RemoteMessageEvent?Cold-start tap payload, if any. Cleared after the first successful read.
| Parameter | Type | Description |
|---|---|---|
| — | — | — |
Returns: RemoteMessageEvent?
capabilities()
func capabilities() async -> ComRaidCapabilitiesReads current notification authorization settings from
UNUserNotificationCenter.
| Parameter | Type | Description |
|---|---|---|
| — | — | — |
Returns: ComRaidCapabilities (authorizationStatus, notificationsEnabled)
Identity
requestPermission(options:) / requestAuthorization(options:)
func requestPermission(options: UNAuthorizationOptions = [.alert, .badge, .sound]) async throws -> Bool
func requestAuthorization(options: UNAuthorizationOptions = [.alert, .badge, .sound]) async throws -> BoolRequests notification permission. When granted, registers for remote
notifications. requestAuthorization is an alias of requestPermission.
| Parameter | Type | Description |
|---|---|---|
options | UNAuthorizationOptions | Authorization options (default alert, badge, sound) |
Returns: Bool — whether permission was granted
register()
func register(tokenWaitTimeout: TimeInterval = 10) async throwsFetches the current APNs token and creates or refreshes a Subscription
(mobileRegisterSubscription). Sends a persisted Keychain credential when
present so a repeat register keeps the same Subscription and Contact. When no
APNs token is stored yet, waits up to tokenWaitTimeout (default 10 seconds) for
setAPNsDeviceToken. On timeout it throws tokenTimeout and still registers
automatically when the token later arrives.
| Parameter | Type | Description |
|---|---|---|
tokenWaitTimeout | TimeInterval | Seconds to wait for the APNs token before throwing tokenTimeout (default 10) |
Returns: Void
onPushTokenRefresh()
func onPushTokenRefresh() async throwsToken rotation: replaces the Subscription token when a credential exists;
otherwise full register (mobileReplaceSubscriptionToken / register).
| Parameter | Type | Description |
|---|---|---|
| — | — | — |
Returns: Void
login(externalUserId:jwt:)
func login(externalUserId: String, jwt: String? = nil) async throwsBinds the Subscription to a known Contact. Pass Identity verification JWT
when the Project requires it. Persists the External user ID in the Keychain with
the Subscription id and credential so setAttributes works after an app restart.
| Parameter | Type | Description |
|---|---|---|
externalUserId | String | Contact External user ID (required, non-empty) |
jwt | String? | Optional Identity verification JWT from your backend |
Returns: Void
logout()
func logout() async throwsMakes the Subscription Inactive and clears its server credential. Clears the
Keychain Subscription id, credential, and External user ID, then immediately
registers a fresh Subscription on a new Anonymous contact. Mobile routes refuse
the old row with 401 unauthorized (missing/mismatched credential) or
409 subscription_inactive.
| Parameter | Type | Description |
|---|---|---|
| — | — | — |
Returns: Void
optOut() / optIn()
func optOut() async throws
func optIn() async throwsContact-level push Channel opt-out / opt-in (all Subscriptions for that Contact).
| Parameter | Type | Description |
|---|---|---|
| — | — | — |
Returns: Void
Properties and Attributes
Automatically collected Properties
| Field | Source |
|---|---|
app_version | Host CFBundleShortVersionString |
sdk_version | ComRaid iOS library version |
device.os / device.os_version / device.model | UIDevice + hardware model id |
locale / language / country | Device locale / region |
timezone | IANA id from the device timezone |
Sent on register, token refresh, and each debounced foreground /session.
There is no public session method.
await ComRaid.shared.setDeviceProperties(
DeviceProperties(appVersion: "1.2.3", model: "iPhone16,1")
)
try await ComRaid.shared.login(externalUserId: "user_123")
try await ComRaid.shared.setAttributes(["plan": "premium", "tier": 2])setDeviceProperties(_:)
func setDeviceProperties(_ properties: DeviceProperties)Optional overrides for automatically collected Properties on the next register / token / session call. Nil fields keep the auto-collected value.
| Parameter | Type | Description |
|---|---|---|
properties | DeviceProperties | Optional overrides (appVersion, sdkVersion, model, os, osVersion, locale, timezone, language, country, extras) |
Returns: Void
setAttributes(_:)
func setAttributes(_ attributes: sending [String: Any]) async throwsUpserts Contact Attributes for the logged-in Contact
(PUT /mobile/subscriptions/{id}/attributes). Requires prior Login.
| Parameter | Type | Description |
|---|---|---|
attributes | [String: Any] | Attribute map (empty map is a successful empty update). Pass NSNull() for a key to remove that Attribute. |
Returns: Void
Remote notifications and ACKs
await ComRaid.shared.handleRemoteNotification(userInfo: userInfo, appInForeground: true)
let options = ComRaid.shared.presentationOptions(for: userInfo)
await ComRaid.shared.handleNotificationResponse(response)
try await ComRaid.shared.presentNotification(event)
await ComRaid.shared.acknowledgeDelivered(deliveryId: id, attributionToken: token)
await ComRaid.shared.acknowledgeOpened(deliveryId: id, attributionToken: token, actionId: "accept")
await ComRaid.shared.flushAcks()Delivered/opened ACKs use a durable UserDefaults queue that survives background
delivery. flushAcks is safe on launch when configure has persisted. Receive
never auto-marks opened. Data-only Notifications (cr_data_only) never
auto-present; use presentNotification for optional tray promotion.
Deep links, images, sounds, badges and threads are covered in Deep links and rich fields. See Acknowledgements.
handleRemoteNotification(userInfo:appInForeground:)
func handleRemoteNotification(userInfo: [AnyHashable: Any], appInForeground: Bool = true) asyncRegisters action categories from cr_* payload keys, enqueues a delivered ACK,
and notifies foreground/background receive listeners.
| Parameter | Type | Description |
|---|---|---|
userInfo | [AnyHashable: Any] | Remote notification userInfo |
appInForeground | Bool | Routes the event to foreground vs background listeners |
Returns: Void
presentationOptions(for:)
func presentationOptions(for userInfo: [AnyHashable: Any]) -> UNNotificationPresentationOptionsOptions for userNotificationCenter(_:willPresent:…). Data-only never
presents; non–data-only follows displayForegroundNotifications.
| Parameter | Type | Description |
|---|---|---|
userInfo | [AnyHashable: Any] | Remote notification userInfo |
Returns: UNNotificationPresentationOptions
handleNotificationResponse(_:)
func handleNotificationResponse(_ response: UNNotificationResponse) asyncEnqueues an opened ACK (optional action button id from the response) and notifies opened listeners (including taps on SDK-presented notifications).
| Parameter | Type | Description |
|---|---|---|
response | UNNotificationResponse | Tap / action response from the system |
Returns: Void
handleNotificationOpen(userInfo:actionId:)
func handleNotificationOpen(userInfo: [AnyHashable: Any], actionId: String? = nil) asyncObjC / RN-friendly open path equivalent to handleNotificationResponse.
| Parameter | Type | Description |
|---|---|---|
userInfo | [AnyHashable: Any] | Notification userInfo |
actionId | String? | Optional action button id |
Returns: Void
presentNotification(_:) / presentNotification(data:)
func presentNotification(_ event: RemoteMessageEvent) async throws
func presentNotification(data: [String: String]) async throwsPosts a local tray item from title/body/actions (optional promotion). Requires a
non-blank title. Body/action taps flow through handleNotificationResponse /
handleNotificationOpen and auto-ACK opened. Presentation fields travel on the
event (see Receive event fields); either overload
rebuilds the payload and shares the RemoteNotificationDisplay.present
path.
| Field | Applied on present? |
|---|---|
imageUrl | Yes — downloaded and attached (same size / time limits as the Notification Service Extension) |
subtitle | Yes — iOS-only display |
sound | Yes — bundled file name, or system sound for blank / default |
badge | Yes — app icon badge |
threadId | Yes — thread identifier for grouping |
androidChannelId | Carried for cross-platform parity; not drawn on iOS |
priority | Carried on the event; does not change local content presentation |
| Parameter | Type | Description |
|---|---|---|
event / data | RemoteMessageEvent / [String: String] | Message to present |
Returns: Void
Listeners
addForegroundMessageListener / addBackgroundMessageListener /
addNotificationOpenedListener / addTokenRefreshListener register
receive/open/token listeners (tokens from ComRaidListenerToken for removal).
setBackgroundHandlerRegistered(_:) marks that a JS background message handler
is registered (RN). Receive still never auto-opens.
acknowledgeDelivered(deliveryId:attributionToken:)
func acknowledgeDelivered(deliveryId: String, attributionToken: String) async -> BoolEnqueues and flushes a delivered ACK. Returns false when ids are blank or the
ACK queue is unavailable.
| Parameter | Type | Description |
|---|---|---|
deliveryId | String | Delivery id (cr_delivery_id) |
attributionToken | String | Attribution token (cr_attribution_token) |
Returns: Bool
acknowledgeOpened(deliveryId:attributionToken:actionId:)
func acknowledgeOpened(deliveryId: String, attributionToken: String, actionId: String? = nil) async -> BoolEnqueues and flushes an opened ACK.
| Parameter | Type | Description |
|---|---|---|
deliveryId | String | Delivery id |
attributionToken | String | Attribution token |
actionId | String? | Optional action button identifier |
Returns: Bool
flushAcks()
func flushAcks() asyncFlushes any durable ACK backlog.
| Parameter | Type | Description |
|---|---|---|
| — | — | — |
Returns: Void
Local schedules
try await ComRaid.shared.schedule(
ComRaidScheduleRequest(
notification: ComRaidNotification(
id: "promo-1",
title: "Reminder",
body: "Your offer expires soon."
),
triggerDate: Date().addingTimeInterval(3600)
)
)
let pending = try ComRaid.shared.pendingSchedules()
try ComRaid.shared.cancel(id: "promo-1")schedule(_:)
func schedule(_ request: ComRaidScheduleRequest) async throwsSchedules a local notification at triggerDate and persists it. Trigger must be
in the future; notification id must be non-empty.
| Parameter | Type | Description |
|---|---|---|
request | ComRaidScheduleRequest | notification + triggerDate |
Returns: Void
pendingSchedules()
func pendingSchedules() throws -> [ComRaidScheduleRequest]Returns persisted schedules whose triggerDate is still in the future, sorted
ascending.
| Parameter | Type | Description |
|---|---|---|
| — | — | — |
Returns: [ComRaidScheduleRequest]
cancel(id:)
func cancel(id: String) throwsCancels a pending local schedule (and marks a matching timer cancelled if present).
| Parameter | Type | Description |
|---|---|---|
id | String | Notification / schedule id |
Returns: Void
Timers
let timer = try await ComRaid.shared.startTimer(
id: "focus-1",
duration: 25 * 60,
notification: ComRaidNotification(
id: "focus-1",
title: "Focus complete",
body: "Your timer has finished."
)
)
_ = try ComRaid.shared.pauseTimer(id: "focus-1")
_ = try await ComRaid.shared.resumeTimer(id: "focus-1")
let all = try ComRaid.shared.timers()
try ComRaid.shared.cancelTimer(id: "focus-1")pauseTimer / resumeTimer / cancelTimer / timers are Local notification
timer lifecycle APIs (parity with Android and React Native).
startTimer(id:duration:notification:)
func startTimer(id: String, duration: TimeInterval, notification: ComRaidNotification) async throws -> ComRaidTimerStarts a countdown timer that fires a local notification when complete.
duration must be finite and greater than 0.
| Parameter | Type | Description |
|---|---|---|
id | String | Timer id (also forces notification.id) |
duration | TimeInterval | Seconds until fire |
notification | ComRaidNotification | Local notification content |
Returns: ComRaidTimer
pauseTimer(id:)
func pauseTimer(id: String) throws -> ComRaidTimerPauses a running timer, clears its pending system request, and stores remaining duration.
| Parameter | Type | Description |
|---|---|---|
id | String | Timer id |
Returns: ComRaidTimer (state .paused)
resumeTimer(id:)
func resumeTimer(id: String) async throws -> ComRaidTimerResumes a paused timer from remaining duration.
| Parameter | Type | Description |
|---|---|---|
id | String | Timer id |
Returns: ComRaidTimer (state .running)
cancelTimer(id:)
func cancelTimer(id: String) throwsCancels a timer and removes its pending schedule.
| Parameter | Type | Description |
|---|---|---|
id | String | Timer id |
Returns: Void
timers()
func timers() throws -> [ComRaidTimer]Lists persisted timers (running, paused, cancelled, completed).
| Parameter | Type | Description |
|---|---|---|
| — | — | — |
Returns: [ComRaidTimer]
Display helpers (RemoteNotificationDisplay)
Use these to build UNNotificationContent and action categories from cr_*
payload keys (app-rendered / data-heavy paths). Not required for typical
OS-presented Notifications.
| Method | Returns | Purpose |
|---|---|---|
content(from:) | UNMutableNotificationContent | Title/body/subtitle/userInfo, cr_sound / cr_badge / cr_thread_id (+ category when actions present) |
categories(from:) | [UNNotificationCategory] | Action buttons from payload |
categoryIdentifier(for:) | String | Stable per button set: comraid.actions.<hash>, so each push can carry its own actions |
registerCategories(from:) | Void (async) | Merges categories into UNUserNotificationCenter |
present(data:) | Void (async throws) | Post a local tray item immediately, with cr_image_url attached |
enrich(_:storageSuiteName:) | UNNotificationContent (async) | Notification Service Extension: attach cr_image_url, register action buttons, send delivered ACK (pass App Group storageSuiteName) |
Setup for images and cold-device action buttons: Images and action buttons (iOS).
Models
| Type | Role |
|---|---|
ComRaidConfiguration | App ID, API base URL, APNsEnvironment, optional storage suite, displayForegroundNotifications |
APNsEnvironment | .sandbox / .production |
DeviceProperties | Overrides for auto-collected Properties on register / token / session |
RemoteMessageEvent / RemoteMessageAction | Receive/open payload (presentation fields in Receive event fields) |
ComRaidListenerToken | Opaque token for removing receive listeners |
RemoteDisplayPolicy | Foreground presentation options for data_only / alert |
ComRaidNotification | Local notification content |
ComRaidScheduleRequest | Local schedule (notification + triggerDate) |
ComRaidCapabilities / ComRaidAuthorizationStatus | Permission snapshot from capabilities() |
ComRaidTimer | Timer state (running / paused / cancelled / completed) |
Receive event fields
RemoteMessageEvent (foreground/background listeners, opened listeners, and
getInitialNotification) carries presentation fields outside sender data.
Optional fields are absent (nil) when not set — never empty strings.
priority is always "high" or "normal" on received events (default
"high").
| Field | Type | Source | Platform notes |
|---|---|---|---|
imageUrl | String? | cr_image_url | Attached on present / NSE enrich (≤ 5 MB, 10 s). OS-drawn alerts need a Notification Service Extension. |
subtitle | String? | cr_subtitle, else aps.alert.subtitle | Drawn on iOS (system alert and presentNotification). |
sound | String? | cr_sound, else aps.sound | Raw value as sent (chime.caf, default). |
badge | Int? (≥ 0) | cr_badge, else aps.badge | App icon badge. |
threadId | String? | cr_thread_id, else aps.thread-id | Thread grouping. |
androidChannelId | String? | cr_android_channel_id | Present when sent (cross-platform parity); not drawn on iOS. |
priority | String ("high" | "normal") | cr_priority, else optional aps priority hint; default "high" | Always present on received events. |
data stays sender keys only — reserved cr_* keys (including cr_subtitle)
are stripped. presentNotification(event) uses these fields; see the method
above.
Deep links and rich fields
API content.push.deep_link arrives as cr_deep_link in userInfo. Read it in
your open handler and navigate yourself — the SDK does not auto-open URLs.
When APNs draws the alert, the system applies sound, subtitle, badge and
thread-id from the aps payload. When the SDK draws it
(presentNotification or RemoteNotificationDisplay.present(data:),
for example for a Data-only Notification) it reads the cr_* keys, falling
back to the matching aps fields:
| Field | iOS behaviour |
|---|---|
image_url / imageUrl | Downloaded over HTTP(S) (≤ 5 MB, 10 s timeout) and attached. JPEG, PNG, GIF or HEIC; on failure the notification shows without it. |
sound | File name of a sound bundled with your app (chime.caf). Blank or default plays the system sound. |
badge | App icon badge. |
thread_id / threadId | Thread identifier: Notifications in the same thread group together. |
subtitle | Applied when APNs draws the alert and when the SDK presents locally. |
actions[].icon and accentColor are Android-only. androidChannelId and
priority travel on the event for parity; they are not drawn into local iOS
content.
Delivered, images, and buttons need a Notification Service Extension
ComRaid always sets mutable-content on alert Notifications. A Notification
Service Extension is required for delivered ACKs when the app is in the
background or killed, and for images / cold-device comraid.actions buttons.
Full setup for Expo, bare React Native, and native iOS:
Images and action buttons (iOS).
Errors
Public ComRaidError cases:
| Case | When |
|---|---|
notConfigured | Called before configure |
notReady | Missing Subscription credential or Login required (e.g. setAttributes) |
tokenTimeout | APNs token did not arrive within tokenWaitTimeout during register (React Native rejects with code tokenTimeout) |
invalidIdentifier | Empty External user ID |
invalidConfiguration(String) | Blank App ID on configure |
triggerMustBeInFuture | Invalid schedule/timer duration or past trigger |
timerNotFound | Unknown timer id |
timerNotPaused | Pause/resume state mismatch |
persistenceFailed | Local store write failed after scheduling |
apiError(String) | Mobile API failure message |
Mobile HTTP error codes (surfaced via apiError when the API returns them):
| Code | HTTP | When |
|---|---|---|
unauthorized | 401 | Missing or mismatched Subscription credential, or credential-less Endpoint. |
subscription_inactive | 409 | Login, opt-out/in, token, Attributes, or session on an Inactive Subscription. |
Objective-C bridge
ComRaidObjCBridge (@objc(ComraidBridge)) exposes the mobile host surface for
React Native / ObjC: configure (including displayForegroundNotifications),
APNs token, onPushTokenRefresh, permission (default or explicit option
strings), register, login/logout, opt-in/out, capabilities,
schedule/cancel/pendingSchedules, startTimer / pauseTimer / resumeTimer /
cancelTimer / timers, setDeviceProperties, Attributes, ACK helpers,
getToken, getInitialNotification, presentNotification,
enrichNotificationRequest (Notification Service Extension), receive event
emitter, and remote handle/presentation helpers.
Direct RemoteNotificationDisplay builders stay Swift-only. Prefer the Swift
ComRaid actor when possible.
Sessions
mobileSubscriptionSession
(POST /mobile/subscriptions/{id}/session) runs automatically on eligible
foregrounds (debounced ~30 minutes since last background). It is HTTP-only:
there is no SDK wrapper, so do not invent a public client method. Android and
React Native inherit the same native behavior.