# iOS

> Add Lemu to an iOS or tvOS app in Swift or Objective-C: events, purchases, known users, screens, app opens, deep links and App Store privacy answers

URL: https://docs.lemuai.com/sdks/ios

The iOS SDK (`LemuAnalytics`) sends events, purchases, known users and screens from your iOS or tvOS app, and records app opens and the deep links that bring people in.

- iOS 13 or later, tvOS 13 or later. Swift and Objective-C.
- No third-party dependencies.
- No advertising identifier (IDFA), no IDFV, and no AdSupport or App Tracking Transparency.
- Events are kept on disk and sent in batches, so nothing is lost offline.

You need the write key of an **App** source. See [Get a write key](https://docs.lemuai.com/sdks/overview#get-a-write-key).

## Install

**Swift Package Manager**

In Xcode, choose **File > Add Package Dependencies...** and enter:
```text
https://github.com/LemuAI/lemu-sdks
```

Choose **Up to Next Major Version** from `1.0.0` and add the `LemuAnalytics` library to your app target.

In a `Package.swift`:
```swift
dependencies: [
    .package(url: "https://github.com/LemuAI/lemu-sdks", from: "1.0.0"),
],
targets: [
    .target(name: "MyApp", dependencies: [
        .product(name: "LemuAnalytics", package: "lemu-sdks"),
    ]),
]
```

**CocoaPods**

```ruby
pod 'LemuAnalytics', '~> 1.0'
```

Then run `pod install`.

## Set up

Call `setup` once, as early as possible, so the first app open is recorded.

**SwiftUI**

```swift
import LemuAnalytics
import SwiftUI

@main
struct BrandApp: App {
    init() {
        Lemu.setup(writeKey: "lpk_...")
    }

    var body: some Scene {
        WindowGroup {
            ContentView()
                .onOpenURL { url in Lemu.trackDeepLink(url) }
        }
    }
}
```

**UIKit**

```swift
import LemuAnalytics

func application(_ application: UIApplication,
                 didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    Lemu.setup(writeKey: "lpk_...")
    return true
}
```

**Objective-C**

```objc
@import LemuAnalytics;

LemuOptions *options = [LemuOptions new];
options.debug = YES;
[Lemu setupWithWriteKey:@"lpk_..." options:options];
```

Every `Lemu` method can be called from any thread, and none of them throws. A bad argument, such as an empty event name or a value JSON can't hold, is skipped and logged when `debug` is on.

**Warning:** If the source lists [Allowed apps](https://docs.lemuai.com/website-pixel/overview#allowed-apps), add your app's bundle identifier, for example `com.brand.app`. Events from any other bundle id are refused.

### Options

Pass options with `Lemu.setup(writeKey: "lpk_...", options: LemuOptions(debug: true))`. All are optional:

| Option | Default | What it does |
|---|---|---|
| `apiHost` | `https://app.lemuai.com` | Where to send events. Change it only if your source's setup steps show another host |
| `debug` | `false` | Logs every call, request and response |
| `requireConsent` | `false` | Sends and stores nothing until `Lemu.setConsent(true)` |
| `flushAt` | `20` | Sends once this many events are queued |
| `flushInterval` | `30` | Sends queued events every this many seconds |
| `maxQueueSize` | `1000` | The most events kept on the device while offline |
| `trackLifecycle` | `true` | `app_installed`, `app_updated`, `app_opened`, `app_backgrounded` |
| `trackDeepLinks` | `true` | `deep_link_opened` from `Lemu.trackDeepLink(_:)` |

## Send events
```swift
Lemu.track(LemuEvent.addToCart, properties: [
    "value": 999,
    "currency": "INR",
    "content_ids": ["SKU1"],
])

Lemu.track("wishlist_shared", properties: ["list_size": 4])
```

Any event name works. For Meta's standard events, use the `LemuEvent` constants (`viewContent`, `addToCart`, `initiateCheckout`, `purchase` and the rest) so the names match exactly. If you already send these events to Meta, the same properties work here. See the [event reference](https://docs.lemuai.com/sdks/events).

Keep contact details out of event properties. Lemu removes keys such as `email`, `phone`, `address` and `password`; send contact details with `identify` instead.

## Purchases
```swift
Lemu.purchase(
    value: 1499.5,
    currency: "INR",
    orderId: "1042",
    contents: [LemuContent(id: "SKU1", quantity: 1, itemPrice: 1499.5, title: "Kurta")],
    properties: ["payment_method": "cod", "coupon": "DIWALI10"]
)
```

`purchase` sends a `Purchase` event straight away instead of waiting for the next batch. `content_ids` and `num_items` are filled in from `contents` when you don't pass them.

**Always pass `orderId`.** Lemu counts one conversion per order. The same order is often reported more than once: by the app, your website, a Shopify webhook, or the app again after a retry. With the order id these count as one order, so journey and campaign revenue isn't counted twice. `value` and `currency` are needed to show revenue at all. See [Conversion events](https://docs.lemuai.com/website-pixel/standard-events#conversion-events).

## Identify users

When someone signs in or gives you their contact details:
```swift
Lemu.identify(userId: "cust_8812", traits: [
    "email": "asha@example.com",
    "phone": "+919876543210",
    "first_name": "Asha",
    "last_name": "Rao",
])
```

`userId` is your own id for the customer. It's stored and sent with every later event until `reset()`. Send phone numbers in international format. On logout:
```swift
Lemu.reset() // new anonymous id, user id cleared
```

`Lemu.anonymousId` returns the id Lemu uses for this install, for example to pass to your backend so server-side events join up with the app's.

## Screens

**SwiftUI**

```swift
CheckoutView()
    .lemuScreen("Checkout")

ProductView(product: product)
    .lemuScreen("Product", properties: ["product_id": product.id])
```

**UIKit**

Turn on automatic screen tracking (it's off by default):
```swift
Lemu.enableAutomaticScreenTracking()
```

Each of your view controllers sends a screen when it appears, named after its class without the `ViewController` suffix (`CheckoutViewController` becomes `Checkout`). Navigation, tab bar, split and page controllers, Apple's own controllers, SwiftUI hosting controllers and child controllers embedded in your own are skipped. To rename a screen, or skip one:
```swift
extension CheckoutViewController: LemuScreenNameProviding {
    var lemuScreenName: String? { "Checkout" } // return nil to send nothing
}
```

**Anywhere**

```swift
Lemu.screen("Checkout", properties: ["step": 2])
```

Screens are stored as `screen_viewed`.

## Deep links and campaigns

Pass every URL that opens the app to `trackDeepLink`. It sends `deep_link_opened` with the `url`, and keeps `utm_source`, `utm_medium`, `utm_campaign`, `utm_term`, `utm_content`, `gclid` and `fbclid` with this and every later event in the session, so a purchase made after tapping a campaign link is credited to that campaign.
```swift
// SwiftUI
WindowGroup { ContentView().onOpenURL { Lemu.trackDeepLink($0) } }

// UIKit, AppDelegate
func application(_ app: UIApplication, open url: URL,
                 options: [UIApplication.OpenURLOptionsKey: Any] = [:]) -> Bool {
    Lemu.trackDeepLink(url, referrer: options[.sourceApplication] as? String)
    return true
}

// UIKit, SceneDelegate
func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {
    URLContexts.forEach { Lemu.trackDeepLink($0.url, referrer: $0.options.sourceApplication) }
}

// Universal links
func scene(_ scene: UIScene, continue userActivity: NSUserActivity) {
    if let url = userActivity.webpageURL { Lemu.trackDeepLink(url) }
}
```

For a cold launch from a link with scenes, also pass the URLs in `scene(_:willConnectTo:options:)` (`connectionOptions.urlContexts` and `connectionOptions.userActivities`). The next `app_opened` carries the link as `url`.

## App lifecycle events

Sent for you unless you set `trackLifecycle: false`:

| Event | When | Properties |
|---|---|---|
| `app_installed` | First launch with the SDK | `version`, `build` |
| `app_updated` | First launch after the version or build changed | `version`, `build`, `previous_version`, `previous_build` |
| `app_opened` | Every time the app comes to the foreground | `from_background`, and `url` when a link opened the app |
| `app_backgrounded` | The app goes to the background | |

If your app had users before you added the SDK, each of them sends `app_installed` once after updating, because the SDK has no record of an earlier version.

## Consent and opt-out

If you must ask before collecting data, start with `requireConsent`:
```swift
Lemu.setup(writeKey: "lpk_...", options: LemuOptions(requireConsent: true))

// later, from your consent prompt
Lemu.setConsent(true)   // sends events held since launch, and remembers the answer
Lemu.setConsent(false)  // discards held and queued events
```

Until consent, nothing is sent and nothing is written to the device, not even the anonymous id. Up to 50 events are held in memory and sent if consent is given. A granted consent is remembered across launches; call `setConsent(false)` to withdraw it.

To let people turn tracking off in your settings screen:
```swift
Lemu.optOut()  // stops everything, clears the queue, remembered across launches
Lemu.optIn()   // turns it back on
Lemu.isOptedOut
```

## Debug logging
```swift
Lemu.setup(writeKey: "lpk_...", options: LemuOptions(debug: true))
```

Every call, request body and response is logged with `os_log` under the subsystem `com.lemuai.analytics`. Watch it in the Xcode console, or in Console.app filtered by that subsystem. Turn `debug` off in release builds.

## Delivery

- Events are kept in `Application Support/Lemu`, excluded from iCloud and device backups, and survive restarts.
- They are sent every 30 seconds, when 20 are queued, when the app goes to the background, and right after a purchase. `Lemu.flush()` sends now.
- Each request carries up to 50 events. Failed requests are retried with increasing waits, up to 5 minutes apart, for up to 20 hours. Events older than 7 days are dropped.
- The queue holds at most 1,000 events. When it's full, the oldest event that isn't a purchase is dropped first.

## App Store privacy

### Privacy manifest

The SDK ships its own privacy manifest (`PrivacyInfo.xcprivacy`, in the package and in the CocoaPods resource bundle `LemuAnalyticsPrivacy`). Xcode adds it to your app's privacy report. It declares:

- `NSPrivacyTracking`: `false`, with no tracking domains.
- Required reason API: UserDefaults, reason `CA92.1`. The SDK keeps its anonymous id, user id, opt-out, consent and the last app version in its own UserDefaults suite.
- Collected data, all linked to the user and none used for tracking:

| Data type | Why it's collected | Purposes |
|---|---|---|
| User ID | The anonymous install id, and your `userId` from `identify` | Analytics, Developer's Advertising or Marketing |
| Email address, phone number, name | Only if you pass them to `identify` | Analytics, Developer's Advertising or Marketing |
| Product interaction | Events, screens, app opens | Analytics, Developer's Advertising or Marketing |
| Purchase history | `purchase()` and other commerce events | Analytics, Developer's Advertising or Marketing |
| Other usage data | Lifecycle and custom events | Analytics |

### App Privacy answers in App Store Connect

Your app's privacy label covers all the data your app collects, including through Lemu. For the data that goes to Lemu:

- **Data used to track you: No.** Lemu doesn't use advertising identifiers, doesn't share data with data brokers, and doesn't link your app's data with other companies' data for advertising. See the note below if you forward data to ad networks.
- **Data linked to you**, for each type you actually send:
  - Contact Info > **Email Address**, **Phone Number**, **Name**: if you call `identify` with them.
  - Identifiers > **User ID**: yes. The SDK always sends an anonymous id, plus your own user id.
  - Purchases > **Purchase History**: if you call `purchase()` or send commerce events.
  - Usage Data > **Product Interaction**: yes (app opens, screens, events).
  - Usage Data > **Other Usage Data**: if you send custom events.
- **Purposes:** **Analytics**, plus **Developer's Advertising or Marketing** if you message these customers through Lemu journeys or campaigns. Add **App Functionality** if your app relies on Lemu data to work.
- **Not collected by the SDK:** location, device ids (IDFA or IDFV), diagnostics, contacts, health, financial info, browsing history, and search history unless you send search terms as events (then also declare Search History).

**Forwarding to ad networks.** If you send Lemu events to an advertising platform, for example through a Meta Conversions API connection, Apple counts that as tracking. Then answer "Data used to track you: Yes" for the shared types, ask permission with App Tracking Transparency first, and only call `identify` with an email or phone after the user allows it.

## Objective-C
```objc
@import LemuAnalytics;

[Lemu track:LemuEvent.addToCart properties:@{@"value": @999, @"currency": @"INR"}];
[Lemu identifyWithUserId:@"cust_8812" traits:@{@"email": @"asha@example.com"}];
[Lemu purchaseWithValue:1499.5 currency:@"INR" orderId:@"1042"
               contents:@[[[LemuContent alloc] initWithId:@"SKU1" quantity:1 itemPrice:@1499.5 title:nil]]
             properties:nil];
[Lemu trackDeepLink:url referrer:nil];
[Lemu setConsent:YES];
```
