Apple SDK (Swift)
The native Apple SDK supports iOS, macOS, Mac Catalyst, tvOS, and watchOS. The
AppPortalTelemetry product provides analytics, sessions, logs, handled errors, crashes, and
real-user monitoring (RUM) through one durable client.
Add Swift package products
Add AppPortalTelemetry to your application target. Add the optional products below for the
capabilities your app uses. Swift 5.9 is the package manifest format, not a minimum compiler
guarantee for precompiled frameworks. Use the Xcode/Swift toolchain specified by the selected
binary release or a compiler that can import those interfaces.
The SDK’s release tooling identifies
AvantiPoint/appportal-apple-packages
as the intended binary SwiftPM repository and generates framework archive URLs under its GitHub
Releases. Those source references do not establish that the repository or a compatible release is
available to install.
Binary installation remains unverified. Before adding a package in Xcode, obtain release instructions identifying an accessible SwiftPM manifest repository, an exact published tag, and its framework archives and checksum metadata for your SDK channel. Verify those references resolve before selecting products. Keep the private implementation checkout separate from application installation; an archive download URL alone is not a SwiftPM manifest repository.
Choose your libraries
AppPortal defines separate products. Each product has a matching Swift import:
| Product / import | Use it for |
|---|---|
AppPortalTelemetry |
Events, sessions, screens, logs, errors, crashes, and RUM |
AppPortalMessaging |
Push registration and Message Center operations |
AppPortalLocation |
Location catalog sync and location-event reporting |
AppPortalSmartLinks |
Resolving and routing installed-app Smart Links |
The optional products include the Telemetry dependency, so configure Telemetry once. Installing Location does not request OS permissions or register geofences. Follow the Messaging and Location guides for those workflows. The app-defined geofence planner is currently a .NET prototype.
Initialize at launch
Start the SDK in an explicit native entry point before handing control to SwiftUI. This covers app initialization after the root call, including construction of the SwiftUI App. The opaque credential already selects the organization, app, and environment.
import AppPortalTelemetry
import SwiftUI
@main
@MainActor
enum StoreEntryPoint {
static func main() {
AppPortal.start("<app-credential>") { options in
// Optional: use your application's chosen user identifier.
options.initialUserId = "customer-42"
// Set this only when your consent policy permits collection immediately.
options.initialConsentState = .granted
}
StoreApp.main()
}
}
// StoreEntryPoint is the only type with @main.
struct StoreApp: App {
var body: some Scene {
WindowGroup { StoreView() }
}
}
UIKit entry point
For a UIKit app, add main.swift to the application target and remove @main (or the older
@UIApplicationMain) from the existing AppDelegate. Use this entry point instead of the
SwiftUI entry point above:
import AppPortalTelemetry
import UIKit
AppPortal.start("<app-credential>") { options in
// Set this only when your consent policy permits collection immediately.
options.initialConsentState = .granted
}
UIApplicationMain(
CommandLine.argc,
CommandLine.unsafeArgv,
nil,
NSStringFromClass(AppDelegate.self)
)
UIKit constructs the existing app delegate after the SDK starts. Keep the app’s scene configuration and delegate methods in place.
AppKit entry point
For a standard AppKit app, add main.swift to the application target and remove @main (or the
older @NSApplicationMain) from the existing AppDelegate:
import AppPortalTelemetry
import AppKit
AppPortal.start("<app-credential>") { options in
// Set this only when your consent policy permits collection immediately.
options.initialConsentState = .granted
}
_ = NSApplicationMain(CommandLine.argc, CommandLine.unsafeArgv)
Keep the target’s main storyboard or main nib setting and its existing application-delegate
connection. NSApplicationMain performs that standard AppKit bootstrap after the SDK starts.
For a programmatic AppKit bootstrap, place the same root call before NSApplication.shared and
delegate construction, then retain your existing application setup and run loop.
Each target must have only one entry point. No application lifecycle forwarding is needed.
The default consent state is pending. A stored decision wins on later launches; call
AppPortal.grantConsent() or AppPortal.revokeConsent() when the user changes that decision.
Start with automatic telemetry
After initialization and consent, the SDK creates the session and observes application lifecycle. Background and resume the app, then open its session to see the available lifecycle context. Supported unhandled failures are collected by the crash integration; report errors your code catches explicitly.
Cold-start timing begins at AppPortal.start, before SDK configuration and storage setup, and
ends at the first active application observation or visible macOS window. The SDK reports cold-start automatically,
including application initialization between those boundaries. Observed returns from background
produce warm-start; duplicate activation and interrupted resumes do not add misleading durations.
Captured fatal exceptions during a pending start report it as failed. These measure native
activation, not first-frame rendering. No manual timer or startup event is needed.
Connect navigation once
Record screens from the navigation host so every page does not need its own capture call.
For UIKit, add this method to the app’s existing UINavigationControllerDelegate:
import AppPortalTelemetry
import UIKit
func navigationController(
_ navigationController: UINavigationController,
didShow viewController: UIViewController,
animated: Bool
) {
AppPortal.trackScreen(String(describing: type(of: viewController)))
}
Keep that delegate assigned to the navigation controller and retained for its lifetime; merge
this callback into existing delegate behavior. UIKit calls
didShow
after a view controller is shown. This example uses controller types as stable screen names.
For SwiftUI, call trackScreen from your app’s central navigation state change with a stable
route name. Other native navigation hosts can use their equivalent callback. Avoid IDs, query
strings, or user-entered titles, and do not instrument the same navigation twice.
Add your own events and logs
Use stable event and screen names. Put searchable dimensions in properties and numeric values in
measurements:
AppPortal.trackEvent(
"checkout.completed",
properties: [
"plan": "growth",
"paymentMethod": "card"
],
measurements: ["value": 49.00]
)
AppPortal.log(
.information,
"Order submitted",
category: "commerce",
properties: ["fulfillment": "delivery"]
)
Identify a signed-in user only after your application knows who they are. Clear the identity on sign-out so later records do not inherit it:
AppPortal.identify(userId: "customer-42")
AppPortal.setContext(key: "storeId", value: "west-12")
// On sign-out:
AppPortal.clearUser()
Measure RUM and capture failures
Use a span when the SDK should measure an operation. Finish the span on every outcome and record a handled error when application code catches one:
let span = AppPortal.startSpan(
"catalog.refresh",
kind: .networkRequest
)
do {
try await catalog.refresh()
span.finish(succeeded: true, httpStatusCode: 200)
} catch {
span.finish(succeeded: false)
AppPortal.addBreadcrumb(
"Catalog refresh failed",
category: "catalog",
level: .warning
)
AppPortal.captureError(error, properties: ["operation": "refresh"])
}
Apple application lifecycle is observed automatically. Record application-specific screen changes
with trackScreen, and use .screenLoad, .networkRequest, or .custom spans for work whose
duration matters to users.
Accepted records are written to app-private durable storage before background delivery. Offline retry and later-launch recovery are SDK responsibilities; applications do not call flush or close.
Push and Message Center
Add the optional AppPortalMessaging product and import it alongside Telemetry. Keep the same
initialized runtime. AppPortalMessages.registerForPush() does not ask the OS for notification
permission or register with APNs; your app owns those actions. After APNs registration succeeds,
pass the returned token from your existing application delegate:
import AppPortalMessaging
import UIKit
func application(
_ application: UIApplication,
didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data
) {
let token = deviceToken.map { String(format: "%02x", $0) }.joined()
AppPortalMessages.setPushToken(token, platform: .iOS)
}
Keep your app’s existing notification-permission flow and APNs registration, and configure the
matching bundle identity and APNs environment in AppPortal. Token capture is queued registration,
not proof that a notification was delivered. Forward an actual user-open action with
AppPortalMessages.trackPushOpened(message) after interpreting the payload through
handlePushPayload; receiving a notification alone is not an open or click.
Message Center access needs a current user-binding token from your authenticated backend as well
as the app credential. The current Apple getMessages and interaction helpers do not attach that
binding header. Use the authenticated HTTP workflow in the Messaging guide
for this server contract; an arbitrary user ID or AppPortal.identify call does not grant access.
The legacy getMessages callback returns an empty list on failure and emits a diagnostic; do not
present that fallback as a verified empty inbox. The HTTP guide distinguishes complete pagination,
failed reads, and acknowledged read/click interactions. Never put an Automation or server key in
the app to replace a user binding.
Follow the session
The SDK associates events, logs, errors, and timings with the current session. Lifecycle observations add foreground/background context. Automatic crash collection covers supported unhandled failures; use the explicit error API above for failures your app catches and recovers from.
Run a test flow, then open Sessions in the Dashboard and select the run’s Session story. Its timeline connects the available signals. Continue with Investigate an app session for the full workflow.
Configuration, privacy and offline recovery
Set options in the same native AppPortal.start call; do not initialize another client from a view.
| Option | Default / behavior |
|---|---|
initialUserId |
No user ID; use one exact opaque ID, not a profile/traits payload |
initialConsentState |
.pending; a saved decision takes precedence |
maxQueueSize / maxBatchSize |
10,000 queued records / 50 per batch; finite bounds, not lossless storage |
captureUnhandledExceptions |
true; supported unhandled capture is separate from explicit handled errors |
appVersion / buildNumber |
Optional application build context; SDK/runtime versions remain SDK-owned |
diagnostics |
Optional SDK diagnostic listener; retain its implementation for the required lifetime |
endpointOverride |
nil; use the SDK-owned Client API endpoint unless an explicit development or Enterprise integration requires an override |
beforeSend |
nil; optional synchronous redaction/drop callback before records are persisted |
captureAppStart |
true; enables the SDK’s automatic native cold/warm startup observations |
captureNetworkRequests |
true; enables network observations from the SDK’s instrumented URL session, not global interception of every request |
These four options are public in the current Apple SDK source. Their presence in a particular binary release must be checked against that release’s generated Swift interface; this guide does not establish that a matching binary release is already published. Use the selected release’s interface and release notes rather than copying configuration APIs from another AppPortal SDK.
An endpointOverride must be an HTTPS base URL without credentials, query strings or fragments.
HTTP is allowed only for literal loopback hosts in local development. beforeSend runs before
persistence, including recovered and automatic records; keep it fast, redact only the intended
fields, and return nil to drop a record. Startup timings measure native activation, not first-frame
rendering. Instrument an application’s URL session explicitly for network observations; existing
sessions and upload/download tasks are not intercepted globally.
The Telemetry product includes its privacy manifest. Collection consent is separate from Apple’s tracking authorization, notification permission and location permission. Starting Telemetry does not make those permission decisions for your app. Do not put secrets, names, email addresses or request bodies into telemetry properties; filtering is not a promise of universal PII removal.
The journal is bounded. Offline delivery, retry and later-launch recovery are SDK-owned, but an evicted record or unsupported termination path is not a successful delivery. Revocation does not erase data already delivered to a server. Keep the same installed app and normal consent policy when checking a saved crash after restart; do not clear storage or add a required flush/close step.
If a record is missing, check consent, endpoint/key pairing, app version and the selected environment, then verify a known observation. Test native fatal recovery on each intended Apple target separately from an explicit handled-error call. For optional push and Message Center use Messaging; it requires its own channel, permission and binding setup.
Next steps
- Review consent and reliable delivery.
- Compare the Android, .NET, and Flutter SDKs.