ComRaidComRaid Docs

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 ComRaid

CocoaPods:

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) throws

Persists 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).

ParameterTypeDescription
configurationComRaidConfigurationappId (cr_app_…), optional apiBaseURL (default https://api.comraid.io), required apnsEnvironment, optional storageSuiteName, optional displayForegroundNotifications (default true)

Returns: Void

setAPNsDeviceToken(_:)

func setAPNsDeviceToken(_ tokenData: Data) async

Stores the APNs device token from application(_:didRegisterForRemoteNotificationsWithDeviceToken:). Notifies addTokenRefreshListener subscribers. When a Subscription credential already exists, also calls /token (same path as onPushTokenRefresh).

ParameterTypeDescription
tokenDataDataRaw APNs device token

Returns: Void

getToken()

func getToken() async throws -> String

Provider push token (APNs hex). Not a ComRaid Endpoint / Subscription id.

ParameterTypeDescription
———

Returns: String — APNs device token hex

getInitialNotification()

func getInitialNotification() -> RemoteMessageEvent?

Cold-start tap payload, if any. Cleared after the first successful read.

ParameterTypeDescription
———

Returns: RemoteMessageEvent?

capabilities()

func capabilities() async -> ComRaidCapabilities

Reads current notification authorization settings from UNUserNotificationCenter.

ParameterTypeDescription
———

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 -> Bool

Requests notification permission. When granted, registers for remote notifications. requestAuthorization is an alias of requestPermission.

ParameterTypeDescription
optionsUNAuthorizationOptionsAuthorization options (default alert, badge, sound)

Returns: Bool — whether permission was granted

register()

func register(tokenWaitTimeout: TimeInterval = 10) async throws

Fetches 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.

ParameterTypeDescription
tokenWaitTimeoutTimeIntervalSeconds to wait for the APNs token before throwing tokenTimeout (default 10)

Returns: Void

onPushTokenRefresh()

func onPushTokenRefresh() async throws

Token rotation: replaces the Subscription token when a credential exists; otherwise full register (mobileReplaceSubscriptionToken / register).

ParameterTypeDescription
———

Returns: Void

login(externalUserId:jwt:)

func login(externalUserId: String, jwt: String? = nil) async throws

Binds 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.

ParameterTypeDescription
externalUserIdStringContact External user ID (required, non-empty)
jwtString?Optional Identity verification JWT from your backend

Returns: Void

logout()

func logout() async throws

Makes 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.

ParameterTypeDescription
———

Returns: Void

optOut() / optIn()

func optOut() async throws
func optIn() async throws

Contact-level push Channel opt-out / opt-in (all Subscriptions for that Contact).

ParameterTypeDescription
———

Returns: Void

Properties and Attributes

Automatically collected Properties

FieldSource
app_versionHost CFBundleShortVersionString
sdk_versionComRaid iOS library version
device.os / device.os_version / device.modelUIDevice + hardware model id
locale / language / countryDevice locale / region
timezoneIANA 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.

ParameterTypeDescription
propertiesDevicePropertiesOptional overrides (appVersion, sdkVersion, model, os, osVersion, locale, timezone, language, country, extras)

Returns: Void

setAttributes(_:)

func setAttributes(_ attributes: sending [String: Any]) async throws

Upserts Contact Attributes for the logged-in Contact (PUT /mobile/subscriptions/{id}/attributes). Requires prior Login.

ParameterTypeDescription
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) async

Registers action categories from cr_* payload keys, enqueues a delivered ACK, and notifies foreground/background receive listeners.

ParameterTypeDescription
userInfo[AnyHashable: Any]Remote notification userInfo
appInForegroundBoolRoutes the event to foreground vs background listeners

Returns: Void

presentationOptions(for:)

func presentationOptions(for userInfo: [AnyHashable: Any]) -> UNNotificationPresentationOptions

Options for userNotificationCenter(_:willPresent:…). Data-only never presents; non–data-only follows displayForegroundNotifications.

ParameterTypeDescription
userInfo[AnyHashable: Any]Remote notification userInfo

Returns: UNNotificationPresentationOptions

handleNotificationResponse(_:)

func handleNotificationResponse(_ response: UNNotificationResponse) async

Enqueues an opened ACK (optional action button id from the response) and notifies opened listeners (including taps on SDK-presented notifications).

ParameterTypeDescription
responseUNNotificationResponseTap / action response from the system

Returns: Void

handleNotificationOpen(userInfo:actionId:)

func handleNotificationOpen(userInfo: [AnyHashable: Any], actionId: String? = nil) async

ObjC / RN-friendly open path equivalent to handleNotificationResponse.

ParameterTypeDescription
userInfo[AnyHashable: Any]Notification userInfo
actionIdString?Optional action button id

Returns: Void

presentNotification(_:) / presentNotification(data:)

func presentNotification(_ event: RemoteMessageEvent) async throws
func presentNotification(data: [String: String]) async throws

Posts 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.

FieldApplied on present?
imageUrlYes — downloaded and attached (same size / time limits as the Notification Service Extension)
subtitleYes — iOS-only display
soundYes — bundled file name, or system sound for blank / default
badgeYes — app icon badge
threadIdYes — thread identifier for grouping
androidChannelIdCarried for cross-platform parity; not drawn on iOS
priorityCarried on the event; does not change local content presentation
ParameterTypeDescription
event / dataRemoteMessageEvent / [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 -> Bool

Enqueues and flushes a delivered ACK. Returns false when ids are blank or the ACK queue is unavailable.

ParameterTypeDescription
deliveryIdStringDelivery id (cr_delivery_id)
attributionTokenStringAttribution token (cr_attribution_token)

Returns: Bool

acknowledgeOpened(deliveryId:attributionToken:actionId:)

func acknowledgeOpened(deliveryId: String, attributionToken: String, actionId: String? = nil) async -> Bool

Enqueues and flushes an opened ACK.

ParameterTypeDescription
deliveryIdStringDelivery id
attributionTokenStringAttribution token
actionIdString?Optional action button identifier

Returns: Bool

flushAcks()

func flushAcks() async

Flushes any durable ACK backlog.

ParameterTypeDescription
———

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 throws

Schedules a local notification at triggerDate and persists it. Trigger must be in the future; notification id must be non-empty.

ParameterTypeDescription
requestComRaidScheduleRequestnotification + triggerDate

Returns: Void

pendingSchedules()

func pendingSchedules() throws -> [ComRaidScheduleRequest]

Returns persisted schedules whose triggerDate is still in the future, sorted ascending.

ParameterTypeDescription
———

Returns: [ComRaidScheduleRequest]

cancel(id:)

func cancel(id: String) throws

Cancels a pending local schedule (and marks a matching timer cancelled if present).

ParameterTypeDescription
idStringNotification / 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 -> ComRaidTimer

Starts a countdown timer that fires a local notification when complete. duration must be finite and greater than 0.

ParameterTypeDescription
idStringTimer id (also forces notification.id)
durationTimeIntervalSeconds until fire
notificationComRaidNotificationLocal notification content

Returns: ComRaidTimer

pauseTimer(id:)

func pauseTimer(id: String) throws -> ComRaidTimer

Pauses a running timer, clears its pending system request, and stores remaining duration.

ParameterTypeDescription
idStringTimer id

Returns: ComRaidTimer (state .paused)

resumeTimer(id:)

func resumeTimer(id: String) async throws -> ComRaidTimer

Resumes a paused timer from remaining duration.

ParameterTypeDescription
idStringTimer id

Returns: ComRaidTimer (state .running)

cancelTimer(id:)

func cancelTimer(id: String) throws

Cancels a timer and removes its pending schedule.

ParameterTypeDescription
idStringTimer id

Returns: Void

timers()

func timers() throws -> [ComRaidTimer]

Lists persisted timers (running, paused, cancelled, completed).

ParameterTypeDescription
———

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.

MethodReturnsPurpose
content(from:)UNMutableNotificationContentTitle/body/subtitle/userInfo, cr_sound / cr_badge / cr_thread_id (+ category when actions present)
categories(from:)[UNNotificationCategory]Action buttons from payload
categoryIdentifier(for:)StringStable 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

TypeRole
ComRaidConfigurationApp ID, API base URL, APNsEnvironment, optional storage suite, displayForegroundNotifications
APNsEnvironment.sandbox / .production
DevicePropertiesOverrides for auto-collected Properties on register / token / session
RemoteMessageEvent / RemoteMessageActionReceive/open payload (presentation fields in Receive event fields)
ComRaidListenerTokenOpaque token for removing receive listeners
RemoteDisplayPolicyForeground presentation options for data_only / alert
ComRaidNotificationLocal notification content
ComRaidScheduleRequestLocal schedule (notification + triggerDate)
ComRaidCapabilities / ComRaidAuthorizationStatusPermission snapshot from capabilities()
ComRaidTimerTimer 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").

FieldTypeSourcePlatform notes
imageUrlString?cr_image_urlAttached on present / NSE enrich (≤ 5 MB, 10 s). OS-drawn alerts need a Notification Service Extension.
subtitleString?cr_subtitle, else aps.alert.subtitleDrawn on iOS (system alert and presentNotification).
soundString?cr_sound, else aps.soundRaw value as sent (chime.caf, default).
badgeInt? (≥ 0)cr_badge, else aps.badgeApp icon badge.
threadIdString?cr_thread_id, else aps.thread-idThread grouping.
androidChannelIdString?cr_android_channel_idPresent when sent (cross-platform parity); not drawn on iOS.
priorityString ("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.

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:

FieldiOS behaviour
image_url / imageUrlDownloaded over HTTP(S) (≤ 5 MB, 10 s timeout) and attached. JPEG, PNG, GIF or HEIC; on failure the notification shows without it.
soundFile name of a sound bundled with your app (chime.caf). Blank or default plays the system sound.
badgeApp icon badge.
thread_id / threadIdThread identifier: Notifications in the same thread group together.
subtitleApplied 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:

CaseWhen
notConfiguredCalled before configure
notReadyMissing Subscription credential or Login required (e.g. setAttributes)
tokenTimeoutAPNs token did not arrive within tokenWaitTimeout during register (React Native rejects with code tokenTimeout)
invalidIdentifierEmpty External user ID
invalidConfiguration(String)Blank App ID on configure
triggerMustBeInFutureInvalid schedule/timer duration or past trigger
timerNotFoundUnknown timer id
timerNotPausedPause/resume state mismatch
persistenceFailedLocal store write failed after scheduling
apiError(String)Mobile API failure message

Mobile HTTP error codes (surfaced via apiError when the API returns them):

CodeHTTPWhen
unauthorized401Missing or mismatched Subscription credential, or credential-less Endpoint.
subscription_inactive409Login, 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.

On this page