Ampli for iOS Swift SDK

Example

See examples of Ampli implementations for the following languages on GitHub:

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

Quick Start

  1. Install the Amplitude SDK

    1pod 'AmplitudeSwift', '~> 1.0.0'
  2. Install the Ampli CLI

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

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

    1Ampli.instance.load(LoadOptions(
    2 environment: AmpliEnvironment.Production
    3))
  5. Identify users and set user properties

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

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

    1Ampli.instance.flush()
  8. Verify implementation status with CLI

    1ampli status [--update]

Install the SDK

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

  1. Add the dependency to your Podfile:

    1pod 'AmplitudeSwift', '~> 1.0.0'
  2. Run pod install in the project directory.

  • Navigate to File > Swift Package Manager > Add Package Dependency. This opens a dialog that allows you to add a package dependency.

  • Enter the URL https://github.com/amplitude/Amplitude-Swift in the search bar.

  • Xcode will automatically resolve to the latest version. Or you can select a specific version.

  • Click the "Next" button to confirm the addition of the package as a dependency.

  • Build your project to make sure the package is properly integrated.

  • Add the following line to your Cartfile.

    1github "amplitude/Amplitude-Swift" ~> 1.0.0

    Check out the Carthage docs for more info.

    Install Ampli CLI

    Install the Ampli CLI from Homebrew or npm.

    1brew tap amplitude/ampli
    2brew install ampli

    1npm 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.

    1ampli pull

    Use Ampli

    Ampli generates a thin facade over the Amplitude SDK which provides convenience methods. The Ampli Wrapper also grants access to every method of the underlying Amplitude SDK through Ampli.instance.client. More details.

    Load

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

    1Ampli.instance.load(LoadOptions(
    2 client: LoadClientOptions(apiKey: AMPLITUDE_API_KEY)
    3));

    1[Ampli.instance load:[LoadOptions initWithApiKey: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. 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.

    1Ampli.instance.identify("userID", Identify(
    2 requiredUserProp: "A trait associated with this user"
    3));

    1[Ampli.instance identify:@"userID" identify:[Identify
    2 requiredUserProp: @"value"
    3 builderBlock:^(IdentifyBuilder *b) {
    4 b.optionalUserProp = true;
    5 }]
    6];

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

    1Ampli.instance.identify("userID", Identify(deviceID: "my_device_id")

    1[Ampli.instance identify:@"userID" identify:[Identify builderBlock:^(IdentifyBuilder *b) {
    2 b.deviceId = @"my_device_id";
    3}]];

    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.

    1Ampli.instance.client.setGroup(groupType:"group type", groupName:"group name")

    1[Ampli.instance.client setGroup:@"group type" groupName:@"group name"];

    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:

    1Ampli.instance.client.setGroup(groupType: "orgID", groupName: ["10", "20"])

    1[Ampli.instance.client setGroup:@"group type" groupName:@[@"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:

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

    The options argument allows you to pass Amplitude fields, like deviceID.

    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.

    1Ampli.instance.track(
    2 SongPlayed(songId: 'songId', songFavorited: true),
    3 options: EventOptions(
    4 deviceId: 'deviceId',
    5 price: 0.99,
    6 quantity: 1
    7 )
    8);

    1AMPEventOptions *options = [AMPEventOptions new];
    2options.deviceId = @"deviceId";
    3options.price = 0.99;
    4options.quantity = 1;
    5
    6[Ampli.instance track:[SongPlayed songId:@"songId" songFavorited:true]
    7 options:options
    8];

    Ampli also generates a class for each event.

    1let myEventObject = SongPlayed(
    2 songId: 'songId', // String,
    3 songFavorited: true, // Bool
    4);

    1AMPBaseEvent *myEventObject = [SongPlayed
    2 songId:@"songId"
    3 songFavorited:true
    4];

    Send all Event objects using the generic track method.

    1Ampli.instance.track(SongPlayed(
    2 songId: 'songId', // String,
    3 songFavorited: true, // Bool
    4);

    1[Ampli.instance track:[SongPlayed
    2 songId:@"songId"
    3 songFavorited:true
    4]];

    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 flushes events in the buffer automatically when flushQueueSize or flushInterval are reached.

    Ampli sends events automatically without calling flush(), but using flush() is useful if you need to send events before the application exits.

    1Ampli.instance.flush()

    1[Ampli.instance flush];

    Ampli CLI

    Pull

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

    1ampli pull

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

    1ampli pull
    2Ampli project is not initialized. No existing `ampli.json` configuration found.
    3? Create a new Ampli project here? Yes
    4? Organization: Amplitude
    5? Workspace: My Workspace
    6? Source: My Source

    Status

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

    1ampli status [--update]

    The output displays status and indicates what events are missing.

    1ampli status
    2Verifying event tracking implementation in source code
    3Song Played (1 location)
    4Song Stopped Called when a user stops playing a song.
    5Events Tracked: 1 missed, 2 total

    Learn more about ampli status.

    Was this page helpful?

    Thanks for your feedback!

    July 16th, 2024

    Need help? Contact Support

    Visit Amplitude.com

    Have a look at the Amplitude Blog

    Learn more at Amplitude Academy

    © 2024 Amplitude, Inc. All rights reserved. Amplitude is a registered trademark of Amplitude, Inc.