RelayGrid logoRelayGrid

iOS SDK Documentation

Turn your users' iPhones into push targets, and report when each push arrives and when it is opened.

No RelayGrid key in your app

Your app never holds an sk_ key. It asks your own backend for a short-lived channel token, and that token only lets the device register itself for the one user your backend vouched for. Your server keeps sending exactly as it does today, with notify() from the Node.js library or the Ruby gem; when the template has an Apple push channel, the user's registered devices get the push.

Android and iOS push is in early access. Your account needs mobile push enabled, so contact support if the push channel's Platform menu only offers RelayGrid.

Builds run from Xcode need a Sandbox channel

A build you run from Xcode is signed with aps-environment = development and gets a sandbox device token. TestFlight, Ad Hoc and App Store builds get production tokens. A token only works in the environment that issued it, so a push sent to the wrong one fails with BadDeviceToken. Set the Apple push channel's APNs environment to Sandbox while you test from Xcode, and to Production for released builds.

Requirements

  • iOS 15 or newer, Swift 5.9 or newer (Xcode 15 or later).
  • The Push Notifications capability on your app target.
  • A RelayGrid push channel with the Apple Push Notification service (iOS) platform, holding your .p8 key, key ID, team ID and bundle ID. An account admin sets it up with the Apple Developer setup guide.
  • Mobile push enabled on your RelayGrid account.
  • A backend endpoint that returns a channel token (step 1).

Installation

The SDK is a Swift package, installed from its git URL with Swift Package Manager. It is not published to a package registry yet, and the repository has no version tags yet, so the dependency follows the master branch. In Xcode, choose File → Add Package Dependencies…, enter the repository URL and set the dependency rule to Branch → master. Or add it to Package.swift:

Swift
dependencies: [
    .package(url: "https://git.relaygrid.dev/relaygrid/relaygrid-ios-sdk.git", branch: "master"),
],
targets: [
    .target(name: "MyApp", dependencies: [.product(name: "RelayGrid", package: "relaygrid-ios-sdk")]),
]

The package has two products. Add RelayGrid to your app target. Add RelayGridNotificationService to a Notification Service Extension target if you want delivery reports and action buttons.

1. Give your backend a channel-token endpoint

This is the one piece of server work. Add an endpoint to your own API that asks RelayGrid for a channel token for the user signed in to your app, with your secret key, and returns it:

HTTP
POST https://relaygrid.dev/api/v1/channel_tokens
Authorization: Bearer sk_...
Content-Type: application/json

{ "external_user_id": "user-123" }
JSON
{ "token": "eyJf...", "expires_in": 3600 }

external_user_id is your own id for the user, the same one you pass to notify(). RelayGrid creates the recipient if it doesn't exist yet, so this works on a user's very first login. With the server SDKs it is one call:

Ruby
relaygrid.channel_tokens.token_for(current_user.id)
TypeScript
(await relaygrid.channelTokens.create({ userId: currentUser.id })).token

Create a restricted key that holds only recipients:token for this, and never ship any sk_ key inside the app. Authenticate the request with your own session and only ever mint a token for the user that session belongs to: the token lets its holder register devices for that one user for an hour.

2. Configure

Call RelayGrid.configure once, early in application(_:didFinishLaunchingWithOptions:). It never asks for notification permission.

Swift
import RelayGrid

try RelayGrid.configure(RelayGridConfig(
    channelTokenProvider: {
        try await MyAPI.shared.post("/relaygrid/token").token
    },
    baseURL: URL(string: "https://relaygrid.dev")!,
    appGroupIdentifier: "group.com.example.myapp"
))
OptionDefaultPurpose
channelTokenProvider—Async closure returning a channel token from your endpoint in step 1. Required.
baseURLhttps://relaygrid.devAPI origin, for self-hosted RelayGrid. The SDK appends /api/v1.
appGroupIdentifiernilApp Group shared with your Notification Service Extension. The offline queue and SDK state live in its container.
timeout30Seconds to wait for each request.
authorizationOptions[.alert, .sound, .badge]What identify() asks the user for.
deepLinkHosts[]Hosts of your universal links, such as shop.example.com or *.example.com. Tapped https links on them go to onDeepLink.

The SDK calls channelTokenProvider on identify(), again before the cached token expires (tokens last an hour; the SDK fetches a new one after 50 minutes), and again whenever RelayGrid answers 401. A bad config throws ConfigurationError from configure, so a misconfigured build fails at startup.

Set appGroupIdentifier if you add a Notification Service Extension, and make it the same group the extension uses (see below). Without an extension you can leave it out.

3. Forward the APNs callbacks

Swift
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    RelayGrid.shared.didRegisterForRemoteNotifications(deviceToken: deviceToken)
}

func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
    RelayGrid.shared.didFailToRegisterForRemoteNotifications(error: error)
}

In a SwiftUI app, put these in a UIApplicationDelegate and attach it with @UIApplicationDelegateAdaptor.

When APNs hands the app a new token, the SDK registers it and removes the old one. On every launch after identify(), configure registers with APNs again, without a prompt, so a token that changed while the app was closed is picked up.

4. Identify after login

Swift
// After your sign-in succeeds:
let enabled = try await RelayGrid.shared.identify()

identify() fetches a channel token, asks the user for notification permission, registers for remote notifications and registers the device for the signed-in user. Call it at a moment that makes sense to your user.

It returns false, and registers nothing, when the user declines. Call it again later, for example from a settings toggle, to try again. If the user allows notifications later in Settings, the next launch registers the device. If a different user signs in on the same phone, identify() moves the device to them.

5. Log out

Swift
// Before your sign-out, while your backend still accepts the session:
try await RelayGrid.shared.logout()

Call it before you end your own session, so your token endpoint can still vouch for the user. logout() removes the device from the user and clears the SDK's local state and offline queue. Local state is cleared even when the request fails.

Taps, deep links and action buttons

Let the SDK own the notification center delegate, and set onDeepLink to route links:

Swift
UNUserNotificationCenter.current().delegate = RelayGridNotificationCenterDelegate.shared

RelayGrid.shared.onDeepLink = { url in
    router.open(url)
}

RelayGridNotificationCenterDelegate shows RelayGrid pushes while the app is in the foreground (foregroundPresentationOptions, which defaults to banner, list and sound) and routes taps on them. Set its fallback to your own delegate to receive everything RelayGrid did not send.

Already own the delegate?

Forward taps instead:

Swift
func userNotificationCenter(
    _ center: UNUserNotificationCenter,
    didReceive response: UNNotificationResponse,
    withCompletionHandler completionHandler: @escaping () -> Void
) {
    if !RelayGrid.shared.handleNotificationResponse(response) {
        handleMyOwnNotification(response)
    }
    completionHandler()
}

handleNotificationResponse(_:) is handleNotificationOpened(userInfo:actionIdentifier:) for a UNNotificationResponse. Both return false for pushes RelayGrid did not send. For a RelayGrid push they report the open and route the tap, on the main queue:

TapWhat happens
Notification bodytrackOpen, then the notification's deep_link, if any.
Action buttontrackOpen, then onNotificationAction. If that returns false (or is unset) and the button has a deep_link, that link. A button without a link never falls back to the body's.
DismissNothing. A dismissal is not an open.

Which links reach onDeepLink

onDeepLink gets links that use a URL scheme your app declares in CFBundleURLTypes, and https links on the hosts in deepLinkHosts. Anything else opens through the system. With onDeepLink unset, every link goes through the system, and your own scheme reaches your onOpenURL or application(_:open:options:).

If your deep links are universal links, list their hosts in deepLinkHosts. iOS does not hand a universal link back to the app that opens it, so without that setting a tap on https://shop.example.com/orders/42 opens Safari instead of your order screen. *.example.com matches any subdomain of example.com but not example.com itself, so list both if you use both. Only https links match.

Swift
try RelayGrid.configure(RelayGridConfig(
    channelTokenProvider: fetchChannelToken,
    deepLinkHosts: ["shop.example.com"]
))

Action buttons

Return true from onNotificationAction when you handled the button. Return false to let the button's own link open instead:

Swift
RelayGrid.shared.onNotificationAction = { action in
    guard action.identifier == "snooze" else { return false }
    reminders.snooze(deliveryId: action.payload.deliveryId)
    return true
}

Buttons only appear with the Notification Service Extension below. If you handle taps entirely your own way, report opens directly:

Swift
if let payload = RelayGridPayload(userInfo: userInfo) {
    RelayGrid.shared.trackOpen(trackingToken: payload.trackingToken)
}

Notification Service Extension (optional)

Without an extension, iOS tells the app nothing when a push arrives, so deliveries go from sent straight to opened, and action buttons don't show. The RelayGridNotificationService product adds both. It depends only on the extension-safe core, so it builds with APPLICATION_EXTENSION_API_ONLY.

  1. In Xcode, choose File → New → Target → Notification Service Extension.
  2. Add the RelayGridNotificationService product to the extension target, not RelayGrid, which uses UIApplication.
  3. Give the app and the extension the same App Groups entitlement, and pass the group to RelayGridConfig(appGroupIdentifier:) in the app.
  4. Replace the generated class:
Swift
import RelayGridNotificationService

final class NotificationService: RelayGridNotificationServiceExtension {
    override var appGroupIdentifier: String? { "group.com.example.myapp" }
}

For each RelayGrid push the extension:

  • writes a delivered event to the shared queue, then sends it, giving up after deliveryReportTimeout (15 seconds) and leaving it for the app to send on its next launch or reconnect. A token the server rejects is dropped;
  • registers a category for the payload's action_buttons and sets the notification's categoryIdentifier;
  • calls prepareContent(_:payload:), which you can override to change the content (attachments, a rewritten title) before it is shown, then shows it.

The extension learns RelayGrid's address from the App Group, where configure stores baseURL. Until the app has been configured once, events wait in the queue. Override baseURL in the extension to fix it there instead. If iOS's time limit runs out first (serviceExtensionTimeWillExpire), the original content is shown, with the button category when it was already registered, and the queued event is kept. Pushes RelayGrid did not send pass through untouched apart from prepareContent.

The extension needs a real device. iOS skips Notification Service Extensions for pushes simulated with xcrun simctl push.

How action buttons work

iOS draws buttons only from a UNNotificationCategory that is registered before the notification is displayed, and RelayGrid's payload carries no aps.category. The extension builds the category from action_buttons (one .foreground action per button, with the ids and titles as sent) and registers it with setNotificationCategories right before display, merged with the categories that are already registered. Some things follow from that:

  • Category ids are relaygrid.actions. plus a hash of the buttons' ids and titles, so pushes with the same buttons share a category. Titles with placeholders make new ones. The 32 most recently used are kept and older RelayGrid categories are removed. Your own categories are never touched.
  • A notification whose category was removed (more than 32 newer button sets since it arrived) loses its buttons in Notification Center. Tapping the body still works.
  • If your app calls setNotificationCategories with only its own categories, RelayGrid's are dropped until the next push registers them again. Read the current set with getNotificationCategories and add yours to it instead.
  • A push that already has a categoryIdentifier keeps it, and no RelayGrid category is registered for it.
  • Without the extension there are no buttons. RelayGridNotificationCategories.category(for:) builds the same category if you want to register it yourself.

The push payload

RelayGrid sends:

JSON
{
  "aps": {
    "alert": { "title": "Your order shipped", "body": "Order 1042 is on its way" },
    "sound": "default",
    "mutable-content": 1
  },
  "relaygrid": {
    "delivery_id": 123,
    "tracking_token": "eyJf...",
    "deep_link": "myapp://orders/1042",
    "action_buttons": [{ "id": "track", "title": "Track", "deep_link": "myapp://orders/1042/track" }]
  }
}

RelayGridPayload(userInfo:) decodes the relaygrid object into deliveryId, trackingToken, deepLink and actionButtons. deep_link and action_buttons are present only when the template sets them. Unknown keys are ignored, so newer servers don't break older apps, and the initializer returns nil for a push RelayGrid did not send.

Delivery tracking and the offline queue

trackOpen(trackingToken:) and trackDelivered(trackingToken:) need no channel token: the tracking token proves the device received that push. With the extension and the notification center delegate in place you never call them yourself.

Events go to a small on-disk queue (a JSON-lines file, at most 500 events, oldest dropped first) and are sent oldest first:

  • on configure, when the network comes back, and right after each new event;
  • after a server error, timeout or lost connection, retried with exponential backoff (2 s, 4 s, 8 s and so on, up to 5 minutes);
  • an event the server rejects (an expired or invalid tracking token, or another 4xx except 408 and 429) is dropped and logged, never retried.

iOS gives an app no signal that a push arrived unless it ships a Notification Service Extension. With one, set appGroupIdentifier so the app and the extension share one queue: the app sends whatever the extension could not.

Errors

Every error the SDK throws is a RelayGridError, so one catch let error as RelayGridError is always enough.

ClassWhen
ConfigurationErrorBad config, or a call before RelayGrid.configure.
ChannelTokenErrorYour channelTokenProvider threw (see underlying) or returned an empty string.
ConnectionErrorNo HTTP response: offline, DNS, TLS, or APNs registration failed.
TimeoutErrorA ConnectionError from a timeout, including APNs never returning a device token.
ApiErrorRelayGrid answered with an error. status, body and errorMessage say why.
AuthenticationError401 or 403: the channel token was refused twice, or the account is not active.
LimitExceededError402.
NotFoundError404: mobile push is not enabled on the account, or the device is unknown.
ValidationError422: RelayGrid rejected the request.
ServerError5xx.
Swift
do {
    try await RelayGrid.shared.identify()
} catch let error as ApiError {
    print(error.status, error.errorMessage ?? "")
} catch {
    print(error)
}

Logging

The SDK logs through os.Logger under the subsystem dev.relaygrid.sdk. Tokens and request bodies are never logged.

Package layout

TargetContents
RelayGridThe app-side API on this page. It uses UIApplication, so it is not extension-safe.
RelayGridNotificationServiceRelayGridNotificationServiceExtension, for your Notification Service Extension. Extension-safe.
RelayGridCoreErrors, the payload parser, categories, the offline queue and the tracking client. Extension-safe, and re-exported by both products.

Sample app

The SDK repository has a SampleApp/ with an app and a Notification Service Extension wired to the package. It has a settings screen for the server and a debug channel-token endpoint, and shows the registration status and a log of taps and deep links. Its README lists what to set before running it on a device: your signing team, bundle ID and App Group, an Apple push channel for the same bundle ID, and a channel-token endpoint.

Running it from Xcode gives it a sandbox token, so send to it through a channel whose APNs environment is Sandbox.