iOS SDKMenu
On this page

iOS SDK

Track signed-in customer activity in your iOS app and send push notifications with images, buttons and delivery reports.

View as MarkdownOpen in ClaudeOpen in ChatGPTUpdated

Use the iOS SDK to see what customers do in your app and reach them with push. Track events and visits for segments and journeys, register devices for push, and report opens and clicks without extra code. It’s written in Swift, has no third-party dependencies and keeps events on the device while it’s offline.

Before you start

  • iOS 13 or later (Mac Catalyst 14 or later), built with Xcode and Swift 5.9 or later.
  • A server you control that can sign a token for the signed-in user. Every Kirora server library does it in one call.
  • For push: an Apple developer account, and an iOS push app in Kirora. See Set up push, and Get your Apple and Firebase keys if you haven’t used either before.

How it works

The SDK runs on your users’ phones, so it never holds an API key. It uses two things instead:

  • A client key (kirora_pk_…): public, safe to ship in the app. It says which workspace the events belong to.
  • A user token: signed by your server for the user who is signed in, so nobody can send events as someone else. The SDK asks your server for one at sign-in and before one expires.

1 Create your keys

In the dashboard, open Developer → SDK. An owner, admin or developer chooses Set up the SDK, which creates both keys. The Secret key is your token secret, shown only once: put it in your server’s environment as KIRORA_SDK_TOKEN_SECRET. The Public key is your client key, and goes in your app.

2 Add a token route to your server

Add a route that signs a token for the user of the current session. Take the user’s id from your own session, never from the app’s request:

TypeScript
// Express, with the Node.js library
import { createUserToken } from '@kirora/node';

app.get('/kirora-token', requireSignedIn, (request, response) => {
  response.set('Cache-Control', 'no-store');
  response.type('text/plain').send(createUserToken(process.env.KIRORA_SDK_TOKEN_SECRET!, String(request.user.id)));
});

Return 401 when nobody is signed in. The Go, .NET, PHP and Laravel libraries sign the same token. In any other language, sign an HS256 JWT with the token secret, with sub set to your id for the user (their contact’s externalId) and exp no more than 24 hours after iat. An hour is a good lifetime.

3 Install the SDK

Swift Package Manager. In Xcode, choose File → Add Package Dependencies, enter the repository and choose Up to Next Major Version from 0.1.0:

Code
https://github.com/kiroratech/kirora-ios

Add the Kirora product to your app target. If you’ll send push with images or buttons, you’ll add KiroraNotificationService to an extension target later. In a Package.swift:

SWIFT
.package(url: "https://github.com/kiroratech/kirora-ios.git", from: "0.1.0")

CocoaPods. Install from the release tag:

Ruby
target 'MyApp' do
  pod 'Kirora', :git => 'https://github.com/kiroratech/kirora-ios.git', :tag => '0.1.0'
end

Run pod install, then open the .xcworkspace it creates.

For a React Native, Expo or Flutter app, use the React Native, Expo or Flutter SDK instead. It includes this one.

4 Start the SDK

Create one client for the app and start it at launch, on the main thread, before your app delegate’s launch method returns:

SWIFT
import Kirora
import UIKit

enum AppServices {
    static let kirora = Kirora(options: KiroraOptions(
        clientKey: "kirora_pk_…",                          // public: safe in the app
        fetchUserToken: { try await MyAPI.kiroraToken() }  // your route from step 2
    ))
}

final class AppDelegate: UIResponder, UIApplicationDelegate {
    func application(
        _ application: UIApplication,
        didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
    ) -> Bool {
        _ = AppServices.kirora
        return true
    }
}

MyAPI.kiroraToken() is your app’s signed-in request to the route from step 2. It returns the token as plain text and throws when the request fails, so the SDK keeps the events and tries again later. In a SwiftUI app, keep the same delegate with @UIApplicationDelegateAdaptor(AppDelegate.self) in your App.

Starting the SDK never blocks your launch: it reads its files in the background and sends nothing until a user signs in.

5 Sign users in and out

SWIFT
let kirora = AppServices.kirora

// Each time the app starts with a signed-in user, and right after they sign in.
try await kirora.identify()

// Before your own sign-out.
await kirora.logout()

Nothing is sent before sign-in: events tracked earlier wait on the device and go as the user who signs in next. An event tracked while one user is signed in never becomes another user’s. logout() tries for up to five seconds to send what’s waiting and stop this device’s pushes for the user, then forgets the rest. Offline, stopping pushes is retried while the app runs, for up to 24 hours.

If the token fails later, in the background, the SDK calls onAuthenticationFailed with .fetchFailed or .refused. Use it to sign the user out, or ask them to sign in again.

6 Track what they do

SWIFT
kirora.track("Order Completed", properties: [
    "order_id": "1042",
    "total": 46.5,
    "currency": "USD"
])
kirora.trackScreenView("Checkout")

track() returns at once and never throws: events go in batches. Properties take strings, numbers, booleans, NSNull(), arrays and dictionaries; dates are sent as ISO 8601 strings. Name events as the naming guide describes, so journeys and segments can match them.

7 Check it works

Sign in on a device or the simulator, track an event, then call await kirora.flush() to send it now. Open the contact in Contacts in Kirora: the event is on their activity. While you build, set logLevel: .debug to see each event and batch in Xcode’s console.

Where the law asks for consent before tracking, start the SDK with requireTrackingConsent: true and pass on the user’s answer:

SWIFT
AppServices.kirora.setTrackingConsent(true)  // they agreed
AppServices.kirora.setTrackingConsent(false) // they refused, or withdrew

Nothing is tracked or kept until the user agrees. The answer is remembered on the device, and false forgets events still waiting. Tracking consent covers events and visits only: push permission and push consent are separate, below.

Send push notifications

Turn push on

  1. In Kirora, add an iOS push app and upload your APNs key (.p8), with its key ID, team ID and your app’s bundle ID. See Set up push.
  2. In Xcode, add the Push Notifications capability to your app target.
  3. In your app, add push: .enabled to the client’s options. If the workspace has several iOS push apps, choose one with push: KiroraPushOptions(pushAppId: "…").
  4. Ask for permission at a moment the user understands, after they’ve signed in:
SWIFT
let permission = await kirora.requestPushPermission() // .granted, .denied, .unanswered or .unsupported

if permission == .granted && userOptedInToMarketing {
    try await kirora.setPushConsent(true) // their consent to marketing push
}

The device is registered at identify() and when permission is granted, and refreshed when the user or token changes. Permission is enough for a transactional push, such as an order update. Campaign and journey push also need the user’s marketing consent, which setPushConsent(_:) records. userOptedInToMarketing stands for their answer to your own opt-in, such as a checkbox: allowing notifications alone isn’t marketing consent. It throws if Kirora didn’t record it, so only show the choice as saved once it returns.

The SDK listens for the APNs token and for taps on its own, with no code of yours.

Add the notification service extension

Images, buttons and delivery reports need a notification service extension. Without it, a push still arrives and taps are still reported, but it shows plainly.

  1. In Xcode, choose File → New → Target → Notification Service Extension. Give it the same minimum iOS version as your app, and keep the Info.plist Xcode generates.

  2. Add the KiroraNotificationService product to the new target, and only to it. With CocoaPods:

    Ruby
    target 'NotificationService' do
      pod 'KiroraNotificationService', :git => 'https://github.com/kiroratech/kirora-ios.git', :tag => '0.1.0'
    end
  3. Replace the generated NotificationService.swift with:

    SWIFT
    import KiroraNotificationService
    
    final class NotificationService: KiroraNotificationServiceExtension {}

The extension needs no keys and no App Group. If your app already has an extension for another provider, call KiroraNotificationService.didReceive(_:withContentHandler:) from it: it returns false for a push that isn’t Kirora’s. Forward serviceExtensionTimeWillExpire() too.

If your app calls setNotificationCategories itself, it replaces the categories Kirora’s buttons use; buttons on pushes already delivered then disappear.

A tap opens the app and is reported as an open, or a click when it has a link. By default, a link opens with UIApplication.open: the browser, or whichever app owns it. To keep your own universal links in the app, list their hosts in your Info.plist as KiroraUniversalLinkHosts, an array such as shop.example.com or *.example.com. A link to a listed host goes to your app delegate’s application(_:continue:restorationHandler:). In a scene-based app, route links yourself with handleDeepLink, or they open in the browser:

SWIFT
let options = KiroraOptions(
    clientKey: "kirora_pk_…",
    handleDeepLink: { url in
        Router.shared.open(url) // return true when your app handled it
    }
)

To act on a tap in your own code, with the push’s data:

SWIFT
let taps = Kirora.addNotificationClickListener { tap in
    // tap.data: the push's data, your own keys included
    // tap.buttonIndex: nil for the notification itself
    // tap.link: the link the SDK opened, if any
}

taps.remove() // when the screen or object that added it goes away

The listener lasts until you call remove(), even if you drop the registration. A tap that launched the app is held for the first listener you add. In the foreground, a Kirora push is always shown; your own notification delegate is asked only about other pushes.

Send through Firebase

If your iOS push app in Kirora sends through Firebase, install and configure FirebaseMessaging in your app, with Firebase’s own APNs setup. The SDK reads Firebase’s token when it runs, so there’s nothing else to add.

Forward callbacks yourself

The SDK hooks into your app delegate to receive the APNs token and taps. To forward them yourself instead, set KiroraAppDelegateProxyEnabled to the Boolean NO in your Info.plist, import UIKit, UserNotifications and Kirora, and call the SDK from your app delegate and your UNUserNotificationCenterDelegate:

SWIFT
func application(_ application: UIApplication,
                 didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    Kirora.application(application, didRegisterForRemoteNotificationsWithDeviceToken: deviceToken)
}

func application(_ application: UIApplication,
                 didFailToRegisterForRemoteNotificationsWithError error: Error) {
    Kirora.application(application, didFailToRegisterForRemoteNotificationsWithError: error)
}

nonisolated func userNotificationCenter(_ center: UNUserNotificationCenter,
                                        didReceive response: UNNotificationResponse,
                                        withCompletionHandler completionHandler: @escaping () -> Void) {
    if Kirora.userNotificationCenter(center, didReceive: response, withCompletionHandler: completionHandler) { return }
    completionHandler() // another provider's push
}

nonisolated func userNotificationCenter(_ center: UNUserNotificationCenter,
                                        willPresent notification: UNNotification,
                                        withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    if Kirora.userNotificationCenter(center, willPresent: notification, withCompletionHandler: completionHandler) { return }
    completionHandler([]) // another provider's push
}

Set your delegate as UNUserNotificationCenter.current().delegate at launch and keep it in memory. When a Kirora method returns true, it has already called the completion handler.

Test a push

Use a real device. On iOS, register your test device to the right push app: Sandbox for a build run from Xcode, Production for TestFlight, ad hoc and App Store builds. See Sandbox or Production. Sign in, allow notifications, then send yourself a test from the push step’s Send test. See Test a push notification. To check delivery and tap reports, send a campaign to a segment with just you in it: test sends aren’t counted.

Visits and app events

  • Visits: a visit starts with a Session Started event, and every event in it carries the same context.sessionId. Activity and time in the foreground keep it going; after 30 minutes away, the next activity starts a new visit. Visits are on by default; trackSessions: false turns them off.
  • App events: trackAppLifecycle: true records Application Installed, Application Updated, Application Opened and Application Backgrounded. It’s off by default.
  • Screens: call trackScreenView(_:) from the screens you care about. Screens aren’t tracked automatically.
  • Context: each event carries the app’s name, version and build, the iOS version, the screen size, the device’s language and time zone and a random id for this install. Never a device model, IDFA or IDFV.

To remove a field, or drop an event, before it’s stored, use beforeSend:

SWIFT
beforeSend: { event in
    var redacted = event
    redacted.properties.removeValue(forKey: "email")
    return redacted // or nil to drop it
}

Options

Option Default What it does
clientKey Required The workspace’s public key (kirora_pk_…).
fetchUserToken None Asks your server for a user token. Times out after 30 seconds.
push Off .enabled, or KiroraPushOptions(pushAppId:) to choose the push app.
requireTrackingConsent false Track and keep nothing until setTrackingConsent(true).
trackSessions true Record Session Started and the visit on every event.
trackAppLifecycle false Record install, update, open and background events.
handleDeepLink None Routes a push’s link. Return true when your app handled it.
onAuthenticationFailed None Called on the main thread when the user’s token fails in the background.
beforeSend None Edits or drops each event before it’s stored.
logLevel .error .none, .error or .debug.
apiUrl https://api.kirora.io For tests against a mock server.

Methods

Method Does
identify(_ token: String? = nil) async throws Signs the user in, with a token from fetchUserToken unless given one; registers for push if allowed; sends waiting events.
logout() async Tries for up to five seconds to send what’s waiting and stop this device’s pushes, then forgets the user.
track(_:properties:) Records an event. Returns at once.
trackScreenView(_:) Records Screen Viewed.
setTrackingConsent(_:) Records the user’s tracking answer.
requestPushPermission() async Shows iOS’s prompt when needed and registers the device.
getPushStatus() async .enabled, .disabled, .denied, .unanswered or .unsupported. Never prompts.
setPushEnabled(_:) async Turns push on or off for this device, for every user. Never prompts.
setPushConsent(_:) async throws Records the signed-in user’s consent to marketing push.
flush() async Sends waiting events now. Rarely needed.
getState() What the SDK knows now, for debugging: signed in, device id, queued events.
destroy() Stops the client. Waiting events stay for the next one.
Kirora.addNotificationClickListener(_:) Hears taps on Kirora pushes and their buttons.

Errors are KiroraApiError (with status, code and retryAfterMs), UserTokenError when fetchUserToken fails, or KiroraError.

Delivery and storage

  • Batches: events go when 20 are waiting, otherwise after about 30 seconds, and when the app goes to the background or comes back online. A batch holds up to 100.
  • Retries: when the device is offline or Kirora is busy, the SDK retries with growing gaps up to about 5 minutes, never sooner than Kirora’s Retry-After. Each event keeps its idempotency key, so a retry is recorded once.
  • On the device: up to 1,000 events wait in the app’s Application Support folder, excluded from backups. Beyond that, the oldest are dropped. Tokens are kept in memory only.
  • Plan limit: past your plan’s tracked events for the month, Kirora refuses further events and the SDK drops them. Sign-in and push still work.
  • Privacy: the SDK uses no IDFA, IDFV or Keychain and never asks for App Tracking Transparency. Both products include a privacy manifest; your App Store disclosures still need to cover the events you send.

Troubleshooting

Symptom Check
Events stay on the device The user is signed in with identify(), tracking consent is given, and your token route returns a token.
401 or a token error The token is signed with this workspace’s secret, names the signed-in user and hasn’t expired.
No push token The Push Notifications capability and a provisioning profile that matches the bundle ID.
Permission granted, status disabled The user is signed in and push is on for the device; check the log with logLevel: .debug.
No image or buttons The notification service extension and its KiroraNotificationService product.
Links open in the browser List your link hosts in KiroraUniversalLinkHosts, or route them in handleDeepLink. In a scene-based app, use handleDeepLink.
No delivery or tap reports Send a campaign, not a test: test sends aren’t counted.

Next steps