# iOS SDK (client)

> Install the Ours Privacy Swift SDK to capture privacy-first analytics in iOS, tvOS, macOS, and watchOS apps. No IDFA, no AppTrackingTransparency prompt.

Source: https://docs.oursprivacy.com/docs/ios-sdk

Use the Ours Privacy Swift SDK to track events and identify users in iOS, tvOS, macOS, and watchOS apps, and to collect app opens, sessions, and screens on iPhone and iPad.

* [Swift Package Manager / GitHub](https://github.com/with-ours/ours-privacy-swift): full README, API reference, and release notes

## Install

In Xcode: **File → Add Package Dependencies…** and enter `https://github.com/with-ours/ours-privacy-swift`. Pick the latest tagged release. Then add `OursPrivacyKit` to your target's dependencies.

> **Migrating from CocoaPods?** Past versions of `OursPrivacy-swift` remain installable from CocoaPods trunk but receive no further updates. New releases ship via Swift Package Manager.

## Quick Start

Create one instance for the lifetime of your app and initialize it with your source's API token:

```swift
import OursPrivacyKit

let op = OursPrivacy(token: "YOUR_API_TOKEN")
Task {
    await op.initialize()
    op.track(event: "Button Pressed")

    // After login
    op.identify(OursPrivacyUserProperties(email: "user@example.com", externalId: "user-123"))
}
```

Events are batched and sent every 10 seconds. Call `op.flush()` to send them immediately, and `op.reset()` on logout to start a new visitor. For default properties, a custom server URL, and the rest of the API, see the [README on GitHub](https://github.com/with-ours/ours-privacy-swift#readme).

### Wait for consent

If your app asks for consent first, start opted out and opt in once the person agrees:

```swift
Task {
    await op.initialize(options: OursPrivacyInitOptions(optedOutByDefault: true))
}

// When consent is granted
op.optInTracking()
```

`optedOutByDefault` applies only until a choice is saved, so a returning user keeps the choice they made. While opted out, the SDK sends nothing, including `track()` and `trackScreen()` calls. `op.optOutTracking()` also clears unsent events, and the next opt-in starts a new session.

## App lifecycle and screens

Turn on automatic lifecycle tracking to fill in app opens, sessions, and engagement in [Mobile Analytics](https://docs.oursprivacy.com/docs/mobile-analytics). It is off by default. Lifecycle and screen events come from iOS apps on iPhone and iPad; tvOS, macOS, watchOS, and iOS apps running on a Mac send only the events you track.

```swift
let op = OursPrivacy(token: "YOUR_API_TOKEN", trackAutomaticEvents: true)
Task { await op.initialize() }
```

| Event                        | When it is sent                                                                                           | Event-specific properties                                  |
| ---------------------------- | --------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------- |
| `$mobile_first_open`         | First tracked open for this installation and source, including when consent is granted after installation | None                                                       |
| `$mobile_app_open`           | Each tracked foreground entry                                                                             | None                                                       |
| `$mobile_session_start`      | First tracked open in a new session                                                                       | None                                                       |
| `$mobile_session_engagement` | A foreground-time checkpoint, screen change, or background transition                                     | `engagement_duration_ms`; `screen_name` when known         |
| `$mobile_session_end`        | When a later open finds the previous session expired, when possible                                       | None                                                       |
| `$mobile_app_update`         | First tracked open after the app version or build changes                                                 | `previous_app_version` and `previous_app_build` when known |
| `$mobile_screen_view`        | Your app calls `trackScreen()` for a new visible screen                                                   | `screen_name`                                              |

A session continues when the app returns to the foreground within 30 minutes, and counts as engaged after 10 seconds in the foreground. `$mobile_session_end` is best effort, because an app can close without warning.

Call `trackScreen()` when a destination appears. The SDK does not detect UIKit or SwiftUI transitions on its own. For example, a SwiftUI screen can send its fixed label:

```swift
struct ScheduleView: View {
    let op: OursPrivacy

    var body: some View {
        Text("Schedule")
            .onAppear { op.trackScreen("Schedule") }
    }
}
```

Pass a fixed label from a list in your app, such as `Schedule`: up to 80 characters, starting with a letter, using only letters, numbers, spaces, underscores, and hyphens. The SDK ignores any other label. Never build a label from a URL, route parameter, patient detail, or screen title.

Manual `track()` and `trackScreen()` calls work whether or not lifecycle tracking is on. Send [standard healthcare events](https://docs.oursprivacy.com/docs/standard-healthcare-events) with the same names and properties as your other sources:

```swift
op.track(event: "appointment_booked", properties: [
    "appointment_id": appointmentId
])
```

Lifecycle and screen events carry device, OS, and app version details, but not your default properties or link attribution. Keep each event under 196 of your own properties and 1 MB; a larger event is still sent, but it doesn't appear in Mobile Analytics.

### Older automatic events and purchases

Automatic tracking also sends the older `$ae_first_open`, `$ae_session`, and `$ae_updated` events. They count differently from the `$mobile_*` events, so build reports and mappings on `$mobile_*`.

StoreKit purchase tracking is a separate option and off by default. Pass `trackAutomaticPurchases: true` to the initializer to send `$ae_iap` events with the product identifier, price, and quantity. Review those values for patient information before you turn this on.

## Web-to-app identity

When your app is opened by a link carrying `ours_visitor_id`, the SDK sets that visitor ID so later events land on the same visitor profile as their web activity. It also reads supported UTM parameters and ad-platform click IDs from the link, attaches them to the events you track afterward, and sends a `$deep_link_opened` event with those values (not the raw URL).

Hand the URL over with `op.trackDeepLink(urlString)`, or pass it at startup with `OursPrivacyInitOptions(initialURL: launchURL)`. If your app already holds the visitor ID, from a WebView or a native bridge, set it directly with `op.setVisitorId("550e8400-e29b-41d4-a716-446655440000")`. To pass the visitor ID to another SDK, such as a [mobile measurement partner](https://docs.oursprivacy.com/docs/mmp), read it with `op.getVisitorId()`.

The SDK hooks nothing in the operating system, so your app has to hand over the URL it was launched with. Cover a universal link and a custom scheme:

```swift
// SceneDelegate: universal link
func scene(_ scene: UIScene, continue userActivity: NSUserActivity) {
    if let url = userActivity.webpageURL?.absoluteString {
        op.trackDeepLink(url)
    }
}

// AppDelegate: custom scheme
func application(_ app: UIApplication, open url: URL,
                 options: [UIApplication.OpenURLOptionsKey: Any] = [:]) -> Bool {
    op.trackDeepLink(url.absoluteString)
    return true
}
```

On iOS, the UTM parameters and click IDs from a link last until the app quits; only the visitor ID persists across a restart. Pass the link to the SDK before you track an event that needs its attribution. Keep patient details out of the links you send people.

[Mobile app attribution](https://docs.oursprivacy.com/docs/mobile-app-attribution) covers how app attribution works end to end, and when you need a mobile measurement partner alongside it.

## Compatibility

* iOS 15+
* tvOS 15+
* macOS 12+
* watchOS 8+
* Xcode with Swift 6 support

No IDFA is collected, so AppTrackingTransparency (ATT) permission is not required on iOS.

## Need Help?

* [GitHub Issues](https://github.com/with-ours/ours-privacy-swift/issues)
* [support@oursprivacy.com](mailto:support@oursprivacy.com)

## Next Steps

* [Client SDKs overview](https://docs.oursprivacy.com/docs/client-overview): pick the right SDK for each surface.
* [Web SDK (JavaScript)](https://docs.oursprivacy.com/docs/web-sdk-javascript): for browser tracking.
* [Android SDK](https://docs.oursprivacy.com/docs/android-sdk): the native Android counterpart.
* [React Native SDK](https://docs.oursprivacy.com/docs/react-native-sdk) or [Flutter SDK](https://docs.oursprivacy.com/docs/flutter-sdk): if you're shipping a cross-platform mobile app.
* [Mobile app attribution](https://docs.oursprivacy.com/docs/mobile-app-attribution): how app attribution works, and when you need a mobile measurement partner.
* [Mobile Analytics](https://docs.oursprivacy.com/docs/mobile-analytics): read app opens, sessions, screens, and tracked events in the dashboard.
