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.

Upgrade to Analytics-Swift


(success)

Success!

This guide assumes you already have a Source in your Segment workspace. If you are creating a new one you can reference the Source Overview Guide

If you're using a previous Segment mobile library such as Analytics-iOS, follow these steps to migrate to the Analytics-Swift library. Analytics-Swift is designed to work with your Objective-C codebase as well.

  1. Import Analytics-Swift
  2. Upgrade your Destinations
  3. Advanced: Upgrade your Middleware
  4. Upgrade Notes: Changes to the Config

1. Import Analytics-Swift

1-import-analytics-swift page anchor

1. Add the SDK with Swift Package Manager

1-add-the-sdk-with-swift-package-manager page anchor
  1. Open your project in Xcode.
  2. If using Xcode 12, go to File > Swift Packages > Add Package Dependency…. If using Xcode 13, go to File > Add Packages…
  3. Enter the git path git@github.com:segmentio/analytics-swift.git for the Package Repository and click Next.
  4. Select the version rules for your application and click Next.
  5. Make sure the Segment Library checkbox is selected.
  6. Click Finish.


You have now added Analytics-Swift to your project. Segment and Sovran show as Swift package dependencies. You can remove the analytics-iOS SDK from your app.

2. Modify your initialized instance

2-modify-your-initialized-instance page anchor
SwiftObjective-C
1
let configuration = Configuration(writeKey: "YOUR_WRITE_KEY")
2
configuration.trackApplicationLifecycleEvents = true
3
configuration.flushAt = 3
4
configuration.flushInterval = 10
5
Analytics.setup(with: configuration)
(success)

Success!

Analytics-Swift supports running multiple instances of the analytics object, so it does not assume a singleton. However, if you're migrating from Analytics-iOS and all your track calls are routed to the Analytics.shared() singleton, you can these calls to your new Analytics-swift object.

Add this extension to your code to ensure that tracking calls written for Analytics-iOS work with Analytics-Swift.

1
@extension Analytics {
2
(SegAnalytics)shared() {
3
return analytics; // or whatever variable name you're using
4
}
5
}

2. Upgrade your destinations

2-upgrade-your-destinations page anchor

If your app uses Segment to route data to destinations through Segment-cloud (for example, cloud-mode destinations), you can skip this step. Analytics-Swift treats device-mode destinations as plugins, and simplifies the process of integrating them into your app. Analytics-Swift supports these device-mode destinations.

1. Include the plugin with SPM

1-include-the-plugin-with-spm page anchor
1
.package(
2
name: "Segment",
3
url: "https://github.com/segment-integrations/analytics-swift-<destination>.git",
4
from: "1.1.3"
5
),

2. Add the plugin to your analytics instance

2-add-the-plugin-to-your-analytics-instance page anchor
1
import Segment
2
import Segment<Destination> // <-- Add this line

Under your Analytics-Swift library setup, call analytics.add(plugin: ...) to add an instance of the plugin to the Analytics timeline.

1
let analytics = Analytics(configuration: Configuration(writeKey: "<YOUR WRITE KEY>")
2
.flushAt(3)
3
.trackApplicationLifecycleEvents(true))
4
analytics.add(plugin: <Destination>())

Your events will now begin to flow to the added destination in Device-Mode.


3. Upgrade middleware to plugins (advanced)

3-upgrade-middleware-to-plugins-advanced page anchor

Middlewares are a powerful mechanism that can augment events collected by the Analytics iOS (Classic) SDK. A middleware is a simple function that is invoked by the Segment SDK and can be used to monitor, modify, augment or reject events. Analytics Swift replaces the concept of middlewares with Enrichment Plugins to give you even more control over your event data. Refer to the Plugin Architecture Overview for more information.

1. Upgrading source middleware

1-upgrading-source-middleware page anchor

Before example


SwiftObjective-C
1
let customizeAllTrackCalls = BlockMiddleware { (context, next) in
2
if context.eventType == .track {
3
next(context.modify { ctx in
4
guard let track = ctx.payload as? TrackPayload else {
5
return
6
}
7
let newEvent = "[New] \(track.event)"
8
var newProps = track.properties ?? [:]
9
newProps["customAttribute"] = "Hello"
10
ctx.payload = TrackPayload(
11
event: newEvent,
12
properties: newProps,
13
context: track.context,
14
integrations: track.integrations
15
)
16
})
17
} else {
18
next(context)
19
}
20
}
21
22
analytics.sourceMiddleware = [customizeAllTrackCalls]

After example


SwiftObjective-C
1
class customizeAllTrackCalls: EventPlugin {
2
let type: PluginType = .enrichment
3
let analytics: Analytics
4
5
public func track(event: TrackEvent) -> TrackEvent? {
6
var workingEvent = event
7
workingEvent.event = "[New] \(event.event)"
8
workingEvent.properties["customAttribute"] = "Hello"
9
return workingEvent
10
}
11
}
12
13
analytics.add(plugin: customizeAllTrackCalls())

2. Upgrading destination middleware

2-upgrading-destination-middleware page anchor

If you don't need to transform all of your Segment calls, and only want to transform the calls going to specific, device-mode destinations, use Destination plugins.

Before example


SwiftObjective-C
1
// define middleware we'll use for amplitude
2
3
let customizeAmplitudeTrackCalls = BlockMiddleware { (context, next) in
4
if context.eventType == .track {
5
next(context.modify { ctx in
6
guard let track = ctx.payload as? TrackPayload else {
7
return
8
}
9
let newEvent = "[Amplitude] \(track.event)"
10
var newProps = track.properties ?? [:]
11
newProps["customAttribute"] = "Hello"
12
ctx.payload = TrackPayload(
13
event: newEvent,
14
properties: newProps,
15
context: track.context,
16
integrations: track.integrations
17
)
18
})
19
} else {
20
next(context)
21
}
22
}
23
24
// configure destination middleware for amplitude
25
26
let amplitude = SEGAmplitudeIntegrationFactory.instance()
27
config.use(amplitude)
28
config.destinationMiddleware = [DestinationMiddleware(key: amplitude.key(), middleware:[customizeAmplitudeTrackCalls])]

After example


SwiftObjective-C
1
class customizeAllTrackCalls: EventPlugin {
2
let type: PluginType = .enrichment
3
let analytics: Analytics
4
5
public func track(event: TrackEvent) -> TrackEvent? {
6
var workingEvent = event
7
workingEvent.event = "[New] \(event.event)"
8
workingEvent.properties["customAttribute"] = "Hello"
9
return workingEvent
10
}
11
}
12
13
// create an instance of the Amplitude plugin
14
15
let amplitudeDestination = AmplitudeDestination()
16
17
// add our enrichment plugin to amplitude
18
19
amplitudeDestination.add(plugin: customizeAmplitudeTrackCalls())
20
21
// add amplitude to analytics instance.
22
23
analytics.add(plugin: amplitudeDestination)

4. Upgrade notes: Changes to the configuration object

4-upgrade-notes-changes-to-the-configuration-object page anchor
(information)

Call Identify as a one-off after migrating to Swift

To preserve the userId for users identified prior to your migration to Swift, you must make a one-off Identify call. This is due to a storage format change between the Analytics-iOS and the Analytics-Swift libraries.

The following option was renamed in Analytics-Swift:

BeforeAfter
defaultProjectSettingsName changed to defaultSettings

The following options were added in Analytics-Swift:

NameDetails
autoAddSegmentDestinationThe analytics client automatically adds the Segment Destination. Set this to false if you want to customize the initialization of the Segment Destination, such as, add destination middleware.

The following options were removed in Analytics-Swift:

Removed OptionDetails
enableAdvertisingTrackingDeprecated
launchOptionsRemoved in favor of the enrichment plugin that adds the default data to the event payloads.
maxQueueSizeDeprecated
recordScreenViewsRemoved in favor of a plugin that provides the same functionality. Use the UIKitScreenTracking plugin.
shouldUseBluetoothDeprecated
shouldUseLocationServicesDeprecated
trackAttributionDataThis feature no longer exists.
trackInAppPurchasesDeprecated
trackPushNotificationsDeprecated

1. Traits are no longer attached to analytics.track() events automatically

1-traits-are-no-longer-attached-to-analyticstrack-events-automatically page anchor

To prevent sending unwanted or unnecessary PII, traits collected in analytics.identify() events are no longer automatically attached to analytics.track() events. To achieve this, you can write a before plugin:

1
import Foundation
2
import Segment
3
4
class InjectTraits: Plugin {
5
let type = PluginType.enrichment
6
weak var analytics: Analytics? = nil
7
8
func execute<T: RawEvent>(event: T?) -> T? {
9
if event?.type == "identify" {
10
return event
11
}
12
13
var workingEvent = event
14
15
if var context = event?.context?.dictionaryValue {
16
context[keyPath: "traits"] = analytics?.traits()
17
18
workingEvent?.context = try? JSON(context)
19
}
20
21
return workingEvent
22
}
23
}

Once you're up and running, you can take advantage of Analytics-Swift's additional features, such as Destination Filters, Functions, and Typewriter support.