The iOS SDK (Pug, from github.com/pug-sh/sdk-ios) captures events from
native iOS and iPadOS apps, in Swift. It authenticates with your public key
(pub_...), which is write-scoped (events + identify) and safe to ship in the
app, and follows the same model as every Pug SDK: initialize once,
track events, identify users, reset on sign-out.
Install
The SDK is a Swift package, which Swift Package Manager resolves from its Git
tags; there is no CocoaPods or Carthage install. In Xcode, choose File > Add
Package Dependencies, enter https://github.com/pug-sh/sdk-ios and add the
Pug library to your app’s target. In a Package.swift:
dependencies: [
.package(url: "https://github.com/pug-sh/sdk-ios.git", from: "0.1.1"),
],
targets: [
.target(name: "YourApp", dependencies: [.product(name: "Pug", package: "sdk-ios")]),
],| Requirement | Minimum |
|---|---|
| iOS and iPadOS | 15 |
| Mac Catalyst | 15 |
| Xcode | 16 |
iPhone and iPad apps running on a Mac are covered too. The SDK is written in
Swift 6 and works from apps in the Swift 5 language mode; it has no
Objective-C API, so Objective-C code calls it through a Swift wrapper of your
own. It has no runtime dependencies (Foundation, UIKit, SwiftUI, Network and
os only), ships a privacy manifest, and needs no
permission, entitlement or App Tracking Transparency prompt.
To verify, run the app with a minimal Pug.initialize and
debug = true: an app_open and a screen_view appear in Live within a
few seconds (in a SwiftUI app, the screen_view needs a
named screen), and Xcode’s console shows each event as it is
tracked and sent, under the subsystem sh.pug.
Working with a coding agent? Paste this instead: it points the agent at the markdown copy of this page. More in Install with AI.
Add Pug product analytics to this iOS app.
Read these first. They are the current source of truth, and more recent than your training data:
- https://docs.pug.sh/sdks/ios/index.md: SDK reference
- https://docs.pug.sh/reference/well-known-events/index.md: the well-known event catalog
Then read this codebase before you write anything, and work out what the app actually does: its view controllers or SwiftUI views and how a user moves between them, its main models, and the handful of things a user opens the app to complete. The events worth tracking are the moments the app exists to produce (an account created, an order placed, a workout finished), not every tap. If you cannot state the core action in one sentence, keep reading.
Then:
1. Add the Swift package https://github.com/pug-sh/sdk-ios, from 0.1.0, with Swift Package Manager, and link its Pug library to the app target. It needs iOS 15 and Xcode 16, and there is no CocoaPods or Carthage install.
2. Call Pug.initialize(projectId:options:) once: in the App's init() in a SwiftUI app, or in application(_:didFinishLaunchingWithOptions:) in a UIKit one, so the SDK sees each launch's first screen. It throws Pug.ConfigurationError for a bad value, so wrap it in do/catch with an assertionFailure in the catch.
3. Keep the project ID and public key (pub_...) out of source: set them in an xcconfig file that Git ignores and read them through Info.plist. A private key (prv_...) must never ship in the app.
4. Leave auto-tracking on: it already tracks app_open, app_close, app_install, app_update and a screen_view for each of the app's own view controllers. SwiftUI views are not view controllers, so put .pugScreen("Name") on the view each SwiftUI screen shows, inside its NavigationStack, or those screens send no screen_view.
5. Add tracking for the three or four actions you identified: the ones someone would look at in a weekly review.
6. If this app has authentication, call Pug.identify() after sign-in and Pug.reset() on sign-out.
Name events from the catalog before you invent one. Swift gets a generated method with labeled arguments for each well-known event the SDK does not track itself, such as Pug.track.purchase(productId: ..., amount: ...), so the compiler checks the properties for you, and the dashboards those events drive stay empty for a custom name. Reach for those first, search the catalog for every action you are about to track, and pass schema-external properties through extras. Durations are TimeInterval seconds. Use Pug.track(_:properties:) with a custom snake_case name only when nothing in the catalog fits, and when you do, tell me which event you considered and why it did not.
iOS consent has two states, starts granted and is saved across launches, which is not the same as the Web SDK: check the consent section before you add a banner. It is not App Tracking Transparency, which Pug does not need, so do not add an ATT prompt for it. Do not use any option that is not in the SDK reference above. When you are done, tell me in one sentence what you concluded this app does, then list the files you changed, the event names you chose, and the build settings I need to set.Initialize
Call Pug.initialize once, with your project ID and public key: every
other call needs it first. Find your project ID in the dashboard URL
(/p/<projectId>), and your public key on your project Overview or under
Settings > API Keys. In a SwiftUI app, call it in your App’s init():
import Pug
import SwiftUI
@main
struct AcmeApp: App {
init() {
do {
try Pug.initialize(projectId: "YOUR_PROJECT_ID", options: Pug.Options(apiKey: "pub_your_public_key"))
} catch {
assertionFailure("Pug was not started: \(error)")
}
}
var body: some Scene {
WindowGroup { ContentView() }
}
}In a UIKit app, the same do/catch goes in
application(_:didFinishLaunchingWithOptions:). Initialized in either place,
before the first scene connects, the SDK sees the first screen and the
app_open of each launch; initialized later, it tracks app_open at once and
screens from the next one that appears.
Pug.initialize throws Pug.ConfigurationError for a blank project ID; a
key that isn’t a public key (pub_...), or holds a space or any character
outside printable ASCII, such as a trailing newline; or an endpoint that isn’t
an http(s) URL with a host and no query or fragment. The assertionFailure
stops a debug build on a bad value, and a release build runs on without
analytics. Pug.initialize does no disk or network work on the calling thread,
so it’s safe on the main thread at launch. A second Pug.initialize is ignored
with a warning until Pug.destroy(), and so is any call made before
Pug.initialize.
Every other call returns at once, can be made from any thread, and never throws: calls run in order on one background thread, and failures are logged.
Options are properties of Pug.Options, each set on its own; the ones left out
keep their defaults.
var options = Pug.Options(apiKey: "pub_your_public_key")
#if DEBUG
options.debug = true
#endif
options.batchMaxSize = 20
options.sessionIdleTimeout = 15 * 60
options.defaultTrackingConsent = .denied
try Pug.initialize(projectId: "YOUR_PROJECT_ID", options: options)| Option | Type | Default | Description |
|---|---|---|---|
endpoint |
URL |
https://api.pugs.dev |
API base URL: set it only when self-hosting. An http URL needs an App Transport Security exception. |
debug |
Bool |
false |
Log debug messages: each event tracked, sent or dropped, and why. Warnings and errors are logged regardless. |
dryRun |
Bool |
false |
Build and log events without sending anything; identify isn’t sent either. Consent is unaffected. |
batchMaxSize |
Int |
10 |
Events per request, at most 1000: a batch goes out once this many are queued, or batchMaxWait after the first of them. |
batchMaxWait |
TimeInterval |
5 |
Seconds the first queued event waits for a full batch. |
batchMaxQueueSize |
Int |
1000 |
Undelivered events to keep; beyond this, the oldest is dropped. |
sessionIdleTimeout |
TimeInterval |
1800 (30 min) |
A session ends after this many seconds without events. |
sessionMaxDuration |
TimeInterval |
86400 (24 h) |
A session ends this many seconds after it began. |
defaultTrackingConsent |
Pug.TrackingConsent |
.granted |
Consent until the user chooses. See Tracking consent. |
persistTrackingConsent |
Bool |
true |
Save the user’s choice for the next launch. See Tracking consent. |
autoOpenCloseEvents |
Bool |
true |
Track app_open and app_close. See Auto-tracking. |
autoScreenViews |
Bool |
true |
Track a screen_view each time one of your view controllers appears on a different screen. |
autoInstallEvents |
Bool |
true |
Track app_install and app_update. |
logger |
(any Pug.Logger)? |
the system log | Receive the SDK’s messages instead. |
storage |
(any Pug.Storage)? |
files | Keep the SDK’s state somewhere else. Pug.MemoryStorage() keeps nothing on the device. |
Durations are TimeInterval seconds. Nothing in Pug.Options throws: a number
out of range is logged and replaced by its default, and a batchMaxSize above
1000 is capped.
By default the SDK logs to the system log under the subsystem sh.pug,
category Pug, which Xcode’s console and Console.app show. A Pug.Logger
implements debug(_:), warning(_:error:) and error(_:error:), is called
from any thread, and gets messages that never contain property values or
traits.
Delivery and storage
Events are sent in batches, one request at a time. A request that fails for a
reason that may pass (no network, a timeout, a server error, a captive portal)
is retried with exponential backoff, from batchMaxWait (at least a second) up
to five minutes; one the server rejects for good is dropped and logged as an
error. Retries reuse the event IDs, which the server deduplicates. Requests are
capped at 4 MiB, and an event over that is dropped when tracked.
When the app enters the background, the SDK sends everything queued and writes
its state to disk, whatever autoOpenCloseEvents says, in a background task
that ends once the sends settle, since iOS may suspend the app from then on. A
send that suspension cuts short is retried.
Undelivered events, identity and consent live in files under the app’s
Application Support directory, in <bundle id>/pug, which is excluded from
backups: they survive restarts but aren’t restored onto another device. Deleting
the app deletes them, so a reinstall is a new install with a new anonymous ID.
Writes are grouped and land within a second, and at once on Pug.flush() and
Pug.destroy(). If a custom storage throws, the SDK falls back to memory
until Pug.destroy() or the process ends; throw from string(forKey:) when a
value may exist but can’t be read, since nil starts a new identity.
The files can be read once the device has been unlocked after a restart. When iOS launches the app in the background before that, the SDK starts at the unlock, and the calls made meanwhile run then.
App extensions, such as a widget or a share extension, can use the SDK too:
track, identify and the rest work as in the app. An extension tracks no
automatic events, and since it has a container of its own, it has its own files
and anonymous ID.
Track events
The first argument is the event name (its kind). Any name works without a
schema; well-known events add typed properties
and richer dashboards.
// Custom event: any name
Pug.track("button_clicked", properties: ["label": "Sign up", "screen": "pricing"])
// Typed well-known event: checked at compile time
Pug.track.purchase(productId: "sku-1", amount: 99.50, currency: "USD")A kind may contain letters, digits, _, . and -; any other kind is dropped
with a warning. Properties are read during the call. A key starting with $ is
reserved for auto-properties and dropped with a
warning: the property, not the event.
Property values map by type:
| Value | Sent as |
|---|---|
String, Substring, Character, an enum with String raw values (its raw value) |
string, cut to 1024 UTF-8 bytes |
Bool |
bool |
Int, Int64, UInt64 and the other integer types |
int; one beyond the signed 64-bit range as a string of its digits |
Double, Float, CGFloat, Decimal |
double; NaN and infinities are dropped |
NSNumber |
by what it holds: bool, int or double |
Date |
timestamp |
| arrays, dictionaries and sets | JSON string, cut to 1024 UTF-8 bytes |
nil, NSNull |
omitted |
anything else, such as UUID, URL or another enum |
its String(describing:), cut to 1024 UTF-8 bytes |
Pug.TrackOptions (on Pug.track and every typed method):
| Option | Type | Default | Description |
|---|---|---|---|
immediate |
Bool |
false |
Send the event on its own right away instead of with the next batch. If the send fails for a reason that may pass, the event joins the queue. |
timestamp |
Date? |
time of the call | When the event happened, for an event recorded after the fact. A time before 1970 or after the year 9999 is logged and replaced by the time of the call. |
Pug.track("order_completed", properties: ["orderId": "o-1"], options: Pug.TrackOptions(immediate: true))Pug.track is also a namespace with a generated method per well-known event,
118 of them: every event in the catalog but the four web-only ones
(page_view, click, rage_click, dead_click) and the five the SDK
tracks itself. Each takes the event’s properties as labeled
arguments (required ones without a default, optional ones defaulting to nil),
then extras:, for properties the schema doesn’t define, and options:.
Pug.track.search(query: "trail shoes")
Pug.track.videoPlay(videoId: "v1", position: 1.5)
Pug.track.addToCart(
productId: "sku-1",
extras: ["coupon": "SPRING"],
options: Pug.TrackOptions(immediate: true)
)
Pug.track.signup()An extra named like an argument is dropped with a warning when that argument is
set. Durations are TimeInterval seconds, sent as text rounded to the
millisecond: position: 1.5 sends position as "1.5s". Values are sent as
given: ranges and patterns in the schemas aren’t checked on the device.
The kinds are constants in Pug.Events (Pug.Events.addToCart is
"add_to_cart"). Pug.track(_:properties:options:) works for a well-known
kind too, and a whole number for a decimal property is sent as a decimal
("price": 10 arrives as 10.0), so both paths fill the same column. With the
automatic events turned off, Pug.track(Pug.Events.appOpen) and the like still
work.
Identify and sessions
Events accumulate against an anonymous ID until you Pug.identify the user on
sign-in, which merges that history into a known profile; call Pug.reset() on
sign-out. Use a stable, unique external ID: your database user ID, not an
email, which can change. Only the first identify after an anonymous session
merges prior activity; the same external ID always resolves to the same
profile, and traits are merged server-side, never removed.
// On sign-in
Pug.identify("user-123", traits: ["email": "user@example.com", "plan": "pro"])
// On sign-out
Pug.reset()
// New session ID, identity kept
Pug.rotateSession()Once the server accepts an identify, events carry the external ID as their
distinct ID. A failed one is logged and not retried, so events keep their
current distinct ID until a later call succeeds. Traits may nest dictionaries
and arrays. A blank ID, or one starting with the reserved cookieless- prefix,
is rejected with an error in the log.
reset() forgets the external ID and starts a new anonymous ID and session; it
does not delete the profile. Events queued before it keep the user they
were tracked for, and are sent without waiting for the next batch.
Pug.flush() sends what’s queued now and writes the SDK’s state to disk;
Pug.destroy() stops the SDK after a final flush of at most ten seconds,
keeping identity, saved consent and undelivered events for the next
Pug.initialize, which waits for the teardown to finish.
| Function | Forgets the external ID | New anonymous ID | New session ID |
|---|---|---|---|
rotateSession() |
No | No | Yes |
reset() |
Yes | Yes | Yes |
Sessions
Sessions group events within a single visit, ending at the idle or max-duration timeout:
The session survives restarts: a launch within the timeouts continues it. Set
them, in seconds, with the sessionIdleTimeout and sessionMaxDuration
options.
Auto-tracking
By default, the SDK tracks these events itself:
| Event | When | Option |
|---|---|---|
app_open |
The app comes to the foreground: it becomes active or enters the foreground, whichever comes first. | autoOpenCloseEvents |
app_close |
The app enters the background. Control Center, a call or a system alert in front of the app is no exit. Sent at once, not batched. | autoOpenCloseEvents |
screen_view |
One of your view controllers appears on a different screen: screenName is its type’s name, screenClass the module-qualified one. |
autoScreenViews |
app_install |
The first launch with the SDK on this device, with appVersion and installSource. |
autoInstallEvents |
app_update |
The first launch of a new app version, with appVersion and previousVersion. |
autoInstallEvents |
Every event also carries the SDK’s auto-properties: device, OS, app version, screen size, locale, time zone, network type and the current screen, and the server adds geo. Reading the network type needs no permission, and the device name is never collected.
Screens are view controllers until you name them. The ones tracked are your
app’s own, from its executable or the frameworks it embeds, whose parent is
none or a navigation, tab bar, split or page view controller. Those containers,
UIKit’s and SwiftUI’s own view controllers (alerts and UIHostingController
among them) and the children of your own containers are skipped. A view
controller that reappears with no other screen in between, as after a share
sheet it presented, isn’t tracked again. Several windows or scenes count as one
app.
SwiftUI views aren’t view controllers, so a SwiftUI-only app gets screen
views only for the screens it names. Name one with pugScreen, on the view the
screen shows, inside its NavigationStack:
NavigationStack {
List(products) { product in
NavigationLink(product.name) { ProductView(product: product) }
}
.pugScreen("Products")
}It’s tracked as a view controller is, with autoScreenViews off too: a
screen_view with its screenName and no screenClass when it appears on a
different screen, and again when it comes back after another. Dismissing a
sheet makes the screen beneath it current again, and a new name is a new
screen. For a screen that is neither, such as a level in a game, call
Pug.screen:
Pug.screen("Level 3")It tracks a screen_view unless that screen is already the current one. Every
event after a screen carries it as $url and the one before as $referrer.
With autoScreenViews off, view controllers are left alone entirely, so the
screens are only the ones you name.
Installs and updates are decided once at launch, from the SDK’s own state
on the device: app_install when the SDK has never run there, and
app_update, carrying previousVersion, on the first launch after
CFBundleShortVersionString changes. An app without a
CFBundleShortVersionString reports neither. installSource is com.apple
for the App Store, com.apple.testflight for TestFlight and for the builds
Xcode installs, which have the same sandbox receipt, and com.apple.simulator
on a simulator.
Adding the SDK to an app that is already out reports each existing user’s
first launch with it as an app_install. Turning autoInstallEvents on later,
in an app already shipping the SDK, doesn’t, and neither does a
destroy-and-initialize cycle.
Background launches track no app_open, app_close or screen_view: an
app that iOS launches in the background, as for a background fetch or a
location update, tracks them from when the user opens it. The events you track
meanwhile are sent as usual.
Consent and privacy
Tracking consent
Consent has two states, .granted and .denied (Pug.TrackingConsent), and
starts granted. To wait for the user’s choice, start denied, and show your
banner while the choice is still pending:
var options = Pug.Options(apiKey: "pub_your_public_key")
options.defaultTrackingConsent = .denied
try Pug.initialize(projectId: "YOUR_PROJECT_ID", options: options)
Pug.whenConsentReady { if Pug.isConsentPending { showConsentBanner() } }
Pug.optInTracking() // the user accepted
Pug.optOutTracking() // the user declinedThe choice is saved, so the banner shows only until the user answers, and an
opt-out made in your settings screen still holds after a restart. While consent
is denied, events and identify are dropped, not kept for later. Opting out
drops queued events unsent and removes the stored identity; opting in again
starts a new anonymous identity.
When the user opts in, the SDK tracks what consent held back: an app_install
or app_update it couldn’t track at launch and, if the app is in the
foreground, app_open and a screen_view of the current screen.
The consent getters never wait. Right after Pug.initialize, while the SDK
reads the saved choice on its own thread, they answer “not known yet”.
Pug.whenConsentReady { ... } runs its closure on the main thread as soon as
they answer for this user, or on the main thread’s next turn if they already
do.
| Property | Returns | Not known yet |
|---|---|---|
Pug.trackingConsent |
The consent in effect | nil |
Pug.isTrackingEnabled |
Whether consent is granted | false |
Pug.isConsentPending |
Whether the user has yet to choose | true |
If your app keeps the choice itself and calls optInTracking() or
optOutTracking() on every launch, set persistTrackingConsent = false: the
choice then lasts until Pug.destroy() or the process ends.
This consent is your app’s own choice about analytics, as for a GDPR banner. It isn’t App Tracking Transparency, which Pug doesn’t need: see Privacy manifest.
Privacy manifest
The SDK ships a privacy manifest (PrivacyInfo.xcprivacy), which Xcode adds to
your app’s privacy report. It declares the data the SDK collects for analytics,
linked to the user and used for no tracking: product interaction (the events),
the user ID that identify passes, and a device ID, the anonymous ID the SDK
gives each install. The SDK calls none of the APIs that need a declared reason.
It reads no advertising identifier, identifierForVendor or device name, and
tracks no one across other companies’ apps, so it needs no App Tracking
Transparency prompt. Your App Store privacy answers still cover what your own
events and traits carry, such as purchases or an email address.
Redacting PII
There’s no device-side redaction and no beforeSend hook: keep PII out of the
properties you pass to Pug.track.
Upgrading
0.1.0 is the first release, so there is nothing to migrate yet.