Skip to content

iOS Ampli Wrapper

Overview

The Ampli Wrapper is a generated, strongly typed API for tracking Analytics events based on your Tracking Plan in Amplitude Data. The tracking library exposes a function for every event in your team’s tracking plan. The function’s arguments correspond to the event’s properties.

Ampli can benefit your app by providing autocompletion for events & properties defined in Data and enforce your event schemas in code to prevent bad instrumentation.

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

Ampli Wrapper versus the Amplitude SDK

We recommend using the Ampli wrapper for all the benefits mentioned above. However, if you want to send events without creating a tracking plan in Amplitude Data, you can learn more about the underlying Amplitude SDK in our SDK Quickstart Guide. Visit the Amplitude iOS SDK documentation.

Quick Start

  1. (Prerequisite) Create a Tracking Plan in Amplitude Data

    Plan your events and properties in Amplitude Data. See detailed instructions here

  2. Install the Amplitude SDK

    pod 'Amplitude', '~> 8.14'
    
  3. Install the Ampli CLI

    npm install -g @amplitude/ampli
    
  4. Pull the Ampli Wrapper into your project

    ampli pull [--path ./Ampli]
    
  5. Initialize the Ampli Wrapper

    Ampli.instance.load(LoadOptions(
      client: LoadClientOptions(apiKey: AMPLITUDE_API_KEY)
    ))
    
  6. Identify users and set user properties

    Ampli.instance.identify("userID", Identify(
        userProp: "A trait associated with this user"
    ))
    
  7. Track events with strongly typed methods and classes

    Ampli.instance.songPlayed(SongPlayed(songId: 'song-1');
    Ampli.instance.track(SongFavorited(songId: 'song-2');
    
  8. Flush events before application exit

    Ampli.instance.flush()
    
  9. Verify implementation status with CLI

    ampli status [--update]
    

Installation

Install the Amplitude SDK

If you haven't already, install the core Amplitude SDK dependencies.

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

  1. Add dependency to Podfile.
    pod 'Amplitude', '~> 8.17.1'
    
  2. Run pod install in the project directory to install the dependency.
  1. Navigate to File > Swift Package Manager > Add Package Dependency. This opens a dialog that allows you to add a package dependency.
  2. Enter the URL https://github.com/amplitude/Amplitude-iOS in the search bar.
  3. Xcode will automatically resolve to the latest version. Or you can select a specific version.
  4. Click the "Next" button to confirm the addition of the package as a dependency.
  5. Build your project to make sure the package is properly integrated.

Add the following line to your Cartfile.

github "amplitude/Amplitude-iOS" ~> 8.17.1
Check out the Carthage docs for more info.

Install the Ampli CLI

You can install the Ampli CLI from Homebrew or NPM.

brew tap amplitude/ampli
brew install ampli
npm install -g @amplitude/ampli

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. Ampli CLI commands are usually run from the project root directory.

ampli pull

API

Load

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

Ampli.instance.load(LoadOptions(
  client: LoadClientOptions(apiKey: AMPLITUDE_API_KEY)
));
#import "Ampli.h"
[Ampli.instance load:[LoadOptions builderBlock:^(LoadOptionsBuilder *b) {
    b.apiKey = AMPLITUDE_API_KEY;
}]];
Arg 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. String. Specifies an API Key. This option overrides the default, which is the API Key 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.

Ampli.instance.identify("userID", Identify(
  userProp: "A trait associated with this user"
));
[Ampli.instance identify:@"userID" event:[Identify userProp:@"A trait associated with this user"]];

The options argument allows you to pass Amplitude fields for this call, such as deviceId.

Ampli.instance.identify("userID", Identify(deviceID: "my_device_id")
[Ampli.instance identify:@"userID" event:[Identify deviceID: "my_device_id"];

Group

Note

This feature is available for Growth customers who have purchased the Accounts add-on.

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

Ampli.instance.setGroup("groupType", "groupName")
[Ampli.instance setGroup:"groupType" value:"groupName"]

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 has performed the specific event, then the count includes the group.

For example, you want to group your users based on what organization they're in by 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 setting groups, define a groupType and groupName. In the previous example, 'orgId' is the groupType and '10' and '15' are the values for groupName. Another example of a groupType could be 'sport' with groupName values like 'tennis' and 'baseball'.

Setting a group also sets the 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 is in multiple groups. For example, if Joe is in 'orgId' '10' and '20', then the groupName is '[10, 20]').

Your code might look like this:

Ampli.instance.setGroup("orgID", ["10", "20"])
[Ampli.instance setGroup:"orgID" value:["10", "20"]]

Track

To track an event, call the event's corresponding function. Every event in your tracking plan gets its own function in the Ampli Wrapper. The call is structured like this:

Ampli.instance.track(_ event: Event, options: EventOptions, extra: MiddlewareExtra)

`objectivec [Ampli.instance track:(Event *)event options:(EventOptions *_Nullable)options extra:(MiddlewareExtra *_Nullable)extra ];

The options argument allows you to pass Amplitude fields, like deviceID. The extra argument lets you pass data to middleware.

Note

EventOptions are set via generic track and aren't exposed on the strongly typed event methods such as Ampli.instance.songPlayed(songId: 'id', songFavorited: true).

For example, in the following code snippet, your tracking plan contains an event called songPlayed. The event is defined 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 defined: price, and quantity. Learn more about Amplitude fields here. The event has one MiddlewareExtra defined: myMiddleware. Learn more about Middleware.

Ampli.instance.track(SongPlayed(songId: 'songId', songFavorited: true), options: EventOptions(deviceId: 'deviceId'))
);
SongPlayed* event = [SongPlayed
    songId:'songId', // NSString *
    songFavorited:true, // NSNumber *
];

EventOptions* options = [EventOptions builderBlock:^(EventOptionsBuilder *builder) {
    builder.deviceId = deviceId;
    builder.userId = userId;
}];

[Ampli.instance track:event options:options]

Ampli also generates a class for each event.

let myEventObject = SongPlayed(
  songId: 'songId', // String,
  songFavorited: true, // Bool
);
SongPlayed *songPlayed = [SongPlayed
    songId:'songId', // NSString *
    songFavorited:true, // NSNumber *
];

You can send all Event objects using the generic track method.

Ampli.instance.track(SongPlayed(
  songId: 'songId', // String,
  songFavorited: true, // Bool
);
[Ampli.instance track:[SongPlayed
    songId:'songId', // NSString *
    songFavorited:true, // NSNumber *
]];

Flush

The Ampli wrapper queues events and sends them on an interval based on the configuration.

Call flush() to immediately send any pending events.

The flush() method returns a promise that can be used to ensure all pending events have been sent before continuing. This can be useful to call prior to application exit.

Ampli.instance.flush()
[ampli flush]

Ampli CLI

Pull

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

ampli pull

You will be prompted to log in to your workspace and select a source.

 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

Learn more about ampli pull.

Status

Verify that events are implemented in your code with the status command:

ampli status [--update]

The output displays status and indicates what events are missing.

➜ 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.

Migration

To migrate to the latest version of Ampli for iOS based on the Amplitude-Swift SDK. You will need to make some changes to your code.

Change your Ampli configuration using the Ampli CLI

  1. Run ampli configure to configure Ampli to use the new runtime.

    ampli configure
    ? Select a platform: iOS
    ? Select a language: Swift
    ? Select a SDK: AmplitudeSwift ~> 1.0 (recommended)
    
  2. Run ampli pull to pull the latest version of your tracking plan. Note that ampli configure will also prompt to run ampli pull for you on runtime change.

    ampli pull
    

Update dependencies

See our migration guide for updating from the maintenance iOS SDK to the latest iOS Swift SDK. This will help you remove the old SDK and add the new SDK to your project.

Ampli updates

For the most part Ampli for the latest iOS SDK is backwards compatible with the maintenance iOS SDK. However, there are some changes you will need to make to your code.

All Amplitude fields are accessible via EventOptions

All Amplitude fields are now accessible via EventOptions. For example, Ampli.instance.track(event, options: EventOptions(price: 0.99, quantity: 1)). In the maintenance SDK only a subset of Amplitude fields were accessible.

Middleware is replaced by Plugins

Ampli for the latest iOS SDK uses Plugins instead of Middleware. Plugins are more flexible and allow you to do more with your data. Any middleware can be converted to an enrichment plugin.

Middleware extra is now on EventOptions

The latest version of Ampli removes the extra argument from track()and identify() and replaces it with EventOptions.extra.


Was this page helpful?