Analytics-Swift Implementation Guide
Once you've installed the Analytics-Swift library, you can start collecting data through Segment's tracking methods:
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.
1// These signatures provide for a typed version of user traits2func identify<T: Codable>(userId: String, traits: T)3func identify<T: Codable>(traits: T)4func identify(userId: String)
The Identify method has these fields:
| Field | Details |
|---|---|
userId optional | The 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 optional | A 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.
1func track(name: String)2// This signature provides a typed version of properties.3func track<P: Codable>(name: String, properties: P?)
The Track method has these fields:
| Field | Details |
|---|---|
name required | The name of the event. Segment recommends you to use human-readable names like Song Played or Status Updated. |
properties optional | The 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.
1func screen(title: String, category: String? = nil)2func screen<P: Codable>(title: String, category: String? = nil, properties: P?)
The Screen method has these fields:
| Field | Details |
|---|---|
name required | The name of the screen, for example Signup or Home. |
properties optional | A 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.
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.
1func group(groupId: String)2func group<T: Codable>(groupId: String, traits: T?)
The Group method has these fields:
| Field | Details |
|---|---|
userId required | The ID for this user in your database. |
groupId required | The ID for this group in your database. |
traits optional | A 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.
func alias(newId: String)
The Alias call has the following fields:
| Field | Details |
|---|---|
newId required | The 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.
@discardableResult func add(plugin: Plugin) -> String
The Find method lets you find a registered plugin from the analytics timeline.
func find<T: Plugin>(pluginType: T.Type) -> Plugin?
The Remove methods lets you remove a registered plugin from the analytics timeline.
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.
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.
public func reset()
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
Analytics iOS only captures the UIApplicationDidFinishLaunchingNotification notification.
UIApplicationDelegate
1// captures if app is closed and launching2application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]?) -> Bool {3// ...4if let url = launchOptions?[.url] {5analytics.openURL(url)6}7}8// captures if an app was already open and returning to the foreground9func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any]) -> Bool {10analytics.openURL(url)11}
UISceneDelegate
1// captures if app is closed and launching2func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {3// NOTE: There could be multiple URLs. This example only handles the first one.4if let url = connectionOptions.urlContexts.first?.url {5analytics.openURL(url)6}7}89// captures if an app was already open and returning to the foreground10func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {11// NOTE: There could be multiple URLs. This example only handles the first one.12if let url = URLContexts.first?.url else {13analytics.openURL(url)14}15}
SwiftUI
1// in the app's Scene code ...2var body: some Scene {3WindowGroup {4ContentView()5.onOpenURL { url in6analytics.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:
1class MyAnonymousIdGenerator: AnonymousIdGenerator {2func newAnonymousId -> String {3return UUID.uuidString4}5}67// in the apps config:8let config = Configuration(writeKey: "WRITEKEY")9.anonymousIdGenerator(MyAnonymousIdGenerator())1011let analytics = Analytics(configuration: config)12