Skip to contentSkip to navigationSkip to topbar
On this page
Looking for more inspiration?Visit the
(information)
You're in the right place! Segment documentation is now part of Twilio Docs. The content you are used to is still here—just in a new home with a refreshed look.

Analytics-Swift Implementation Guide


Once you've installed the Analytics-Swift library, you can start collecting data through Segment's tracking methods:

  • Identify
  • Track
  • Screen
  • Group
  • Alias

Identify

identify page anchor

The Identify method lets you tie a user to their actions and record traits about them. This includes a unique user ID and any optional traits you know about them like their email, name, or address. The traits option can include any information you want to tie to the user. When using any of the reserved traits, be sure the information reflects the name of the trait. For example, email should always be a string of the user's email address.

Method signatureSwiftObjective-C
1
// These signatures provide for a typed version of user traits
2
func identify<T: Codable>(userId: String, traits: T)
3
func identify<T: Codable>(traits: T)
4
func identify(userId: String)

The Identify method has these fields:

FieldDetails
userId optionalThe database ID for this user. If you don't know who the user is yet, you can omit the userId and just record traits. You can read more in the identify reference
traits optionalA dictionary of traits you know about the user, like their email or name. You can read more about traits in the identify reference.

The Track method lets you record the actions your users perform. Every action triggers an event, which also has associated properties that the track method records.

Method signatureSwiftObjective-C
1
func track(name: String)
2
// This signature provides a typed version of properties.
3
func track<P: Codable>(name: String, properties: P?)

The Track method has these fields:

FieldDetails
name requiredThe name of the event. Segment recommends you to use human-readable names like Song Played or Status Updated.
properties optionalThe structure of properties for the event. If the event was Product Added to cart, it may have properties like price and productType.

The Screen method lets you record whenever a user sees a screen in your mobile app, along with optional extra information about the page being viewed.

You can record a Screen event whenever the user opens a screen in your app. This could be a view, fragment, dialog or activity depending on your app.

Not all integrations support Screen, so when it's not supported explicitly, the Screen method tracks as an event with the same parameters.

Method signatureSwiftObjective-C
1
func screen(title: String, category: String? = nil)
2
func screen<P: Codable>(title: String, category: String? = nil, properties: P?)

The Screen method has these fields:

FieldDetails
name requiredThe name of the screen, for example Signup or Home.
properties optionalA dictionary of properties for the screen. A screen Photo Feed might have properties like Feed Type or Sort Order.

You can enable automatic screen tracking by using this example plugin(link takes you to an external page).

Once you add the plugin to your project, add it to your Analytics instance:

analytics.add(plugin: UIKitScreenTracking())

The Group method lets you associate an individual user with a group — whether it's a company, organization, account, project, or team. This includes a unique group identifier and any additional group traits you may have, like company name, industry, or number of employees. You can include any information you want to associate with the group in the traits option. When using any of the reserved group traits, be sure the information reflects the name of the trait. For example, email should always be a string of the user's email address.

Method signatureSwiftObjective-C
1
func group(groupId: String)
2
func group<T: Codable>(groupId: String, traits: T?)

The Group method has these fields:

FieldDetails
userId requiredThe ID for this user in your database.
groupId requiredThe ID for this group in your database.
traits optionalA dictionary of traits you know about the group. Things like: name or website.

The Alias method is used to merge two user identities, effectively connecting two sets of user data as one. When this method is called, the newId value overwrites the old userId. If no userId is currently set, the newId associates with future events as the userId. This is an advanced method and may not be supported across the entire destination catalog.

Method signatureSwiftObjective-C
func alias(newId: String)

The Alias call has the following fields:

FieldDetails
newId requiredThe newId of the user you want to map to.

The Analytics Swift utility methods help you work with plugins from the analytics timeline. They include:

There's also the Flush method to help you manage the current queue of events.


The Add method allows you to add a plugin to the analytics timeline.

Method signatureExample use
@discardableResult func add(plugin: Plugin) -> String

The Find method lets you find a registered plugin from the analytics timeline.

Method signatureExample use
func find<T: Plugin>(pluginType: T.Type) -> Plugin?

The Remove methods lets you remove a registered plugin from the analytics timeline.

Method signatureExample use
func remove(plugin: Plugin)

The Flush method lets you force flush the current queue of events regardless of what the flushAt and flushInterval is set to.

Method signatureExample use
public func flush()

The Reset method clears the SDK's internal stores for the current user and group. This is useful for apps where users log in and out with different identities on the same device over time.

Method signatureExample use
public func reset()
(information)

Info

The reset method doesn't clear the userId from connected client-side integrations. If you want to clear the userId from connected client-side destination plugins, you'll need to call the equivalent reset method for that library.


Since there a various deep linking scenarios you may want to account for, the analytics.openURL(...) method was added so you can track deep links in any situation. Where and how you implement the method will depend on your app lifecycle setup (for example, UIApplicationDelegate vs. UISceneDelegate or UIKit vs. SwiftUI). The following snippets outline what your implementation might look like in a few different scenarios.

(warning)

Warning

Analytics iOS only captures the UIApplicationDidFinishLaunchingNotification notification.

UIApplicationDelegate

1
// captures if app is closed and launching
2
application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]?) -> Bool {
3
// ...
4
if let url = launchOptions?[.url] {
5
analytics.openURL(url)
6
}
7
}
8
// captures if an app was already open and returning to the foreground
9
func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any]) -> Bool {
10
analytics.openURL(url)
11
}

UISceneDelegate

1
// captures if app is closed and launching
2
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
3
// NOTE: There could be multiple URLs. This example only handles the first one.
4
if let url = connectionOptions.urlContexts.first?.url {
5
analytics.openURL(url)
6
}
7
}
8
9
// captures if an app was already open and returning to the foreground
10
func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {
11
// NOTE: There could be multiple URLs. This example only handles the first one.
12
if let url = URLContexts.first?.url else {
13
analytics.openURL(url)
14
}
15
}

SwiftUI

1
// in the app's Scene code ...
2
var body: some Scene {
3
WindowGroup {
4
ContentView()
5
.onOpenURL { url in
6
analytics.openURL(url)
7
}
8
}
9
}
10
}

If you call this method with a valid URL parameter, a Segment Deep Link Opened track event triggers.



To generate custom anonymousIds instead of relying on the ones Segment creates, you can use the following configuration option:

1
class MyAnonymousIdGenerator: AnonymousIdGenerator {
2
func newAnonymousId -> String {
3
return UUID.uuidString
4
}
5
}
6
7
// in the apps config:
8
let config = Configuration(writeKey: "WRITEKEY")
9
.anonymousIdGenerator(MyAnonymousIdGenerator())
10
11
let analytics = Analytics(configuration: config)
12

View the Analytics Swift changelog on GitHub(link takes you to an external page).