
Amplitude Data supports tracking analytics events from iOS apps written in Swift and Objective-C.

## Quick start

1. [Install the Amplitude SDK](#install-the-amplitude-sdk).

   ```bash
   pod 'AmplitudeSwift', '~> 1.0'
   ```

2. [Install the Ampli CLI](#install-the-ampli-cli).

   ```bash
   npm install -g @amplitude/ampli
   ```

3. [Pull the Ampli Wrapper into your project](#pull).

   ```bash
   ampli pull [--path ./Ampli]
   ```

4. [Initialize the Ampli Wrapper](#load).

   ```swift
   Ampli.instance.load(LoadOptions(
     environment: AmpliEnvironment.YourEnvironment
   ))
   ```

5. [Identify users and set user properties](#identify).

   ```swift
   Ampli.instance.identify("userID", Identify(
       userProp: "A trait associated with this user"
   ))
   ```

6. [Track events with strongly typed methods and classes](#track).

   ```swift
   Ampli.instance.songPlayed(SongPlayed(songId: "song-1")
   Ampli.instance.track(SongFavorited(songId: "song-2")
   ```

7. [Flush events before application exit](#flush).

   ```swift
   Ampli.instance.flush()
   ```

8. [Verify implementation status with CLI](#status).

   ```shell
   ampli status [--update]
   ```

## Install the SDK

Install the Amplitude Analytics iOS SDK with CocoaPods, Carthage, or Swift Package Manager.

{% tabs tabs="CocoaPods, Swift Package Manager, Carthage" %}
{% tab name="CocoaPods" %}

1. Add the dependency to your `Podfile`:

   ```ruby
   platform :ios, '16.0'

   target 'YourApp' do
     pod 'AmplitudeSwift', '~> 1.0'
   end
   ```

2. Run `pod install` in the project directory.
{% /tab %}
{% tab name="Swift Package Manager" %}
3. Navigate to *File > Swift Package Manager > Add Package Dependency*. A dialog opens that lets you add a package dependency.
4. Enter the URL `https://github.com/amplitude/Amplitude-Swift` in the search bar.
5. Xcode automatically resolves to the latest version, or you can select a specific version.
6. Select **Next** to confirm the addition of the package as a dependency.
7. Build your project to confirm the package is properly integrated.
{% /tab %}
{% tab name="Carthage" %}
Add the following line to your `Cartfile`.

```bash
github "amplitude/Amplitude-Swift" ~> 1.0
```

Refer to the [Carthage docs](https://github.com/Carthage/Carthage#adding-frameworks-to-an-application) for more info.
{% /tab %}
{% /tabs %}

## Install the Ampli CLI

Install the [Ampli CLI](/docs/sdks/ampli/ampli-cli) from Homebrew or npm.

{% code-group %}
```bash Homebrew
brew tap amplitude/ampli
brew install ampli
```

```bash npm
npm install -g @amplitude/ampli
```
{% /code-group %}

### Pull the Ampli Wrapper into your project

Run the Ampli CLI `pull` command to log in to Amplitude Data and download the strongly typed Ampli Wrapper for your tracking plan. Run Ampli CLI commands from the project root directory.

```bash
ampli pull
```

{% callout type="note" heading="Attach properties to your source" %}
After you add new events or properties to your tracking plan, attach them to your source in Amplitude Data. The `ampli pull` command only includes events and properties attached to the selected source. If you don't attach new properties to your source, they don't appear in the generated Ampli Wrapper code.
{% /callout %}

## Use Ampli

Ampli generates a thin facade over the Amplitude SDK that provides convenience methods. The Ampli Wrapper also grants access to every method of the underlying Amplitude SDK through `Ampli.instance.client`. Refer to [More details](/docs/sdks/ampli#wrapping-the-amplitude-sdk).

### Import

Import the Amplitude SDK in your Swift file:

```swift
import AmplitudeSwift
```

### Load

Initialize Ampli in your code. The `load()` method accepts configuration option arguments:

{% code-group %}
```swift Swift
// Using API key directly
Ampli.instance.load(LoadOptions(
    client: LoadClientOptions(apiKey: AMPLITUDE_API_KEY)
))

// Using environment from tracking plan
Ampli.instance.load(LoadOptions(
    environment: AmpliEnvironment.YourEnvironment
))
```

```objectivec Obj-c
// Using API key directly
[Ampli.instance load:[LoadOptions initWithApiKey:AMPLITUDE_API_KEY]];

// Using environment from tracking plan
[Ampli.instance load:[LoadOptions initWithEnvironment:AmpliEnvironmentYourEnvironment]];
```
{% /code-group %}

| Argument      | Description                                                                                                                                                     |
| ------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `LoadOptions` | Required. Specifies configuration options for the Ampli Wrapper.                                                                                                |
| `instance`    | Required if `apiKey` isn't set. Specifies an Amplitude instance. By default, Ampli creates an instance for you.                                                 |
| `apiKey`      | Required if `instance` isn't set. Specifies an API Key. This option overrides the default, which is the API Key configured in your tracking plan.              |
| `environment` | Optional. Specifies the environment name from your tracking plan. Replace `YourEnvironment` with the actual environment name configured in your tracking plan. |
| `disabled`    | Optional. Specifies whether the Ampli Wrapper does any work. When true, all calls to the Ampli Wrapper are no-ops. Useful in local or development environments. |

### Identify

Call `identify()` to identify a user in your app and associate all future events with their identity, or to set their properties.

Just as the Ampli Wrapper creates types for events and their properties, it creates types for user properties.

The `identify()` function accepts an optional `userId`, optional user properties, and optional `options`.

For example, your tracking plan contains a user property called `userProp`. The property's type is a string.

{% code-group %}
```swift Swift
Ampli.instance.identify("userID", Identify(
    requiredUserProp: "A trait associated with this user",
    optionalUserProp: "Another trait"
))
```

```objectivec Obj-c
[Ampli.instance identify:@"userID" identify:[Identify
    requiredUserProp: @"value"
    builderBlock:^(IdentifyBuilder *b) {
        b.optionalUserProp = true;
    }]
];
```
{% /code-group %}

The options argument lets you pass [Amplitude fields](/docs/apis/analytics/http-v2#event-array-keys) for this call, such as `deviceId`.

{% code-group %}
```swift Swift
Ampli.instance.identify("userID", Identify(), options: EventOptions(deviceId: "my_device_id"))
```

```objectivec Obj-c
[Ampli.instance identify:@"userID" identify:[Identify builderBlock:^(IdentifyBuilder *b) {
    b.deviceId = @"my_device_id";
}]];
```
{% /code-group %}

### Group

Call `setGroup()` to associate a user with their group (for example, their department or company). The `setGroup()` function accepts a required `groupType`, and `groupName`.

{% code-group %}
```swift Swift
Ampli.instance.client.setGroup(groupType:"group type", groupName:"group name")
```

```objectivec Obj-c
[Ampli.instance.client setGroup:@"group type" groupName:@"group name"];
```
{% /code-group %}

Amplitude supports assigning users to groups and performing queries, such as Count by Distinct, on those groups. If at least one member of the group performs the specific event, the count includes the group.

For example, you group users by organization using an `orgId`. Joe is in `orgId` `10`, and Sue is in `orgId` `15`. Sue and Joe both perform a certain event. You can query their organizations in the Event Segmentation Chart.

When you set groups, define a `groupType` and `groupName`. In this example, `orgId` is the `groupType` and `10` and `15` are the values for `groupName`. Another example of a `groupType` is `sport` with `groupName` values like `tennis` and `baseball`.

Setting a group also sets `groupType:groupName` as a user property, and overwrites any existing `groupName` value set for that user's `groupType`, and the corresponding user property value. `groupType` is a string, and `groupName` can be either a string or an array of strings to indicate that a user belongs to multiple groups. For example, if Joe is in `orgId` `10` and `20`, then the `groupName` is `[10, 20]`.

Your code might look like this:

{% code-group %}
```swift Swift
Ampli.instance.client.setGroup(groupType: "orgID", groupName: ["10", "20"])
```

```objectivec Obj-c
[Ampli.instance.client setGroup:@"group type" groupName:@[@"10", @"20]];
```
{% /code-group %}

### Track

To track an event, call the event's corresponding function. Every event in your tracking plan has its own function in the Ampli Wrapper. The call uses this structure:

```swift
Ampli.instance.track(_ event: Event, options: EventOptions)
```

The `options` argument lets you pass [Amplitude fields](/docs/apis/analytics/http-v2#event-array-keys), like `deviceID`.

{% callout type="note" heading="" %}
Set EventOptions through generic track. Ampli doesn't expose them on strongly typed event methods such as `Ampli.instance.songPlayed(songId: 'id', songFavorited: true)`.
{% /callout %}

For example, your tracking plan contains an event called `songPlayed` with two required properties: `songId` and `songFavorited`. The property type for `songId` is string, and `songFavorited` is a boolean.

The event has two [Amplitude fields](/docs/apis/analytics/http-v2#event-array-keys) defined: `price` and `quantity`.

{% code-group %}
```swift Swift
Ampli.instance.track(
    SongPlayed(songId: 'songId', songFavorited: true),
    options: EventOptions(
        deviceId: 'deviceId',
        price: 0.99,
        quantity: 1
    )
);
```

```objectivec Obj-c
AMPEventOptions *options = [AMPEventOptions new];
options.deviceId = @"deviceId";
options.price = 0.99;
options.quantity = 1;

[Ampli.instance track:[SongPlayed songId:@"songId" songFavorited:true]
                options:options
];
```
{% /code-group %}

Ampli also generates a class for each event.

{% code-group %}
```swift Swift
let myEventObject = SongPlayed(
    songId: 'songId', // String,
    songFavorited: true, // Bool
);
```

```objectivec Obj-c
AMPBaseEvent *myEventObject = [SongPlayed
    songId:@"songId"
    songFavorited:true
];
```
{% /code-group %}

Send all Event objects using the generic track method.

{% code-group %}
```swift Swift
Ampli.instance.track(SongPlayed(
    songId: 'songId', // String,
    songFavorited: true, // Bool
);
```

```objectivec Obj-c
[Ampli.instance track:[SongPlayed
    songId:@"songId"
    songFavorited:true
]];
```
{% /code-group %}

### Flush

The Ampli Wrapper queues events and sends them on an interval based on the configuration. Ampli flushes the buffer automatically when it reaches `flushQueueSize` or `flushInterval`.

Call `flush()` to send any pending events immediately. The `flush()` method returns a promise you can use to confirm Ampli sent all pending events before continuing. Call `flush()` before application exit to send queued events.

{% code-group %}
```swift Swift
Ampli.instance.flush()
```

```objectivec Obj-c
[Ampli.instance flush];
```
{% /code-group %}

## Ampli CLI

### Pull

The `pull` command downloads the Ampli Wrapper code to your project. Run the `pull` command from the project root.

```bash
ampli pull
```

Ampli prompts you to log in to your workspace and select a source.

```bash
➜ ampli pull
Ampli project is not initialized. No existing `ampli.json` configuration found.
? Create a new Ampli project here? Yes
? Organization: Amplitude
? Workspace: My Workspace
? Source: My Source
```

### Status

Verify that your code implements events with the status command:

```bash
ampli status [--update]
```

The output displays status and indicates what events are missing.

```bash
➜ ampli status
✘ Verifying event tracking implementation in source code
 ✔ Song Played (1 location)
 ✘ Song Stopped Called when a user stops playing a song.
Events Tracked: 1 missed, 2 total
```

Learn more about [`ampli status`](/docs/sdks/ampli/ampli-cli#status).
