Upgrade to Analytics-Swift
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.
- Import Analytics-Swift
- Upgrade your Destinations
- Advanced: Upgrade your Middleware
- Upgrade Notes: Changes to the Config
- Open your project in Xcode.
- If using Xcode 12, go to File > Swift Packages > Add Package Dependency…. If using Xcode 13, go to File > Add Packages…
- Enter the git path
git@github.com:segmentio/analytics-swift.gitfor the Package Repository and click Next. - Select the version rules for your application and click Next.
- Make sure the Segment Library checkbox is selected.
- 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.
1let configuration = Configuration(writeKey: "YOUR_WRITE_KEY")2configuration.trackApplicationLifecycleEvents = true3configuration.flushAt = 34configuration.flushInterval = 105Analytics.setup(with: configuration)
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() {3return analytics; // or whatever variable name you're using4}5}
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.package(2name: "Segment",3url: "https://github.com/segment-integrations/analytics-swift-<destination>.git",4from: "1.1.3"5),
1import Segment2import 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.
1let analytics = Analytics(configuration: Configuration(writeKey: "<YOUR WRITE KEY>")2.flushAt(3)3.trackApplicationLifecycleEvents(true))4analytics.add(plugin: <Destination>())
Your events will now begin to flow to the added destination in Device-Mode.
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.
Before example
1let customizeAllTrackCalls = BlockMiddleware { (context, next) in2if context.eventType == .track {3next(context.modify { ctx in4guard let track = ctx.payload as? TrackPayload else {5return6}7let newEvent = "[New] \(track.event)"8var newProps = track.properties ?? [:]9newProps["customAttribute"] = "Hello"10ctx.payload = TrackPayload(11event: newEvent,12properties: newProps,13context: track.context,14integrations: track.integrations15)16})17} else {18next(context)19}20}2122analytics.sourceMiddleware = [customizeAllTrackCalls]
After example
1class customizeAllTrackCalls: EventPlugin {2let type: PluginType = .enrichment3let analytics: Analytics45public func track(event: TrackEvent) -> TrackEvent? {6var workingEvent = event7workingEvent.event = "[New] \(event.event)"8workingEvent.properties["customAttribute"] = "Hello"9return workingEvent10}11}1213analytics.add(plugin: customizeAllTrackCalls())
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
1// define middleware we'll use for amplitude23let customizeAmplitudeTrackCalls = BlockMiddleware { (context, next) in4if context.eventType == .track {5next(context.modify { ctx in6guard let track = ctx.payload as? TrackPayload else {7return8}9let newEvent = "[Amplitude] \(track.event)"10var newProps = track.properties ?? [:]11newProps["customAttribute"] = "Hello"12ctx.payload = TrackPayload(13event: newEvent,14properties: newProps,15context: track.context,16integrations: track.integrations17)18})19} else {20next(context)21}22}2324// configure destination middleware for amplitude2526let amplitude = SEGAmplitudeIntegrationFactory.instance()27config.use(amplitude)28config.destinationMiddleware = [DestinationMiddleware(key: amplitude.key(), middleware:[customizeAmplitudeTrackCalls])]
After example
1class customizeAllTrackCalls: EventPlugin {2let type: PluginType = .enrichment3let analytics: Analytics45public func track(event: TrackEvent) -> TrackEvent? {6var workingEvent = event7workingEvent.event = "[New] \(event.event)"8workingEvent.properties["customAttribute"] = "Hello"9return workingEvent10}11}1213// create an instance of the Amplitude plugin1415let amplitudeDestination = AmplitudeDestination()1617// add our enrichment plugin to amplitude1819amplitudeDestination.add(plugin: customizeAmplitudeTrackCalls())2021// add amplitude to analytics instance.2223analytics.add(plugin: amplitudeDestination)
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:
| Before | After |
|---|---|
defaultProjectSettings | Name changed to defaultSettings |
The following options were added in Analytics-Swift:
| Name | Details |
|---|---|
autoAddSegmentDestination | The 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 Option | Details |
|---|---|
enableAdvertisingTracking | Deprecated |
launchOptions | Removed in favor of the enrichment plugin that adds the default data to the event payloads. |
maxQueueSize | Deprecated |
recordScreenViews | Removed in favor of a plugin that provides the same functionality. Use the UIKitScreenTracking plugin. |
shouldUseBluetooth | Deprecated |
shouldUseLocationServices | Deprecated |
trackAttributionData | This feature no longer exists. |
trackInAppPurchases | Deprecated |
trackPushNotifications | Deprecated |
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:
1import Foundation2import Segment34class InjectTraits: Plugin {5let type = PluginType.enrichment6weak var analytics: Analytics? = nil78func execute<T: RawEvent>(event: T?) -> T? {9if event?.type == "identify" {10return event11}1213var workingEvent = event1415if var context = event?.context?.dictionaryValue {16context[keyPath: "traits"] = analytics?.traits()1718workingEvent?.context = try? JSON(context)19}2021return workingEvent22}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.