Skip to content

Commit 252f27b

Browse files
committed
update swift setup guide
1 parent feb4c31 commit 252f27b

File tree

1 file changed

+258
-49
lines changed

1 file changed

+258
-49
lines changed

src/connections/auto-instrumentation/swift-setup.md

Lines changed: 258 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ Learn how to connect an existing source, integrate dependencies, turn on Auto-In
1212
> info "Regional availability"
1313
> Auto-Instrumentation isn't supported in EU workspaces.
1414
15-
## Step 1: Get your source write key
15+
## Before you start
1616

1717
You need the `writeKey` from an existing Segment source. To find it:
1818

@@ -21,60 +21,265 @@ You need the `writeKey` from an existing Segment source. To find it:
2121
3. From the source's overview tab, go to **Settings > API Keys**.
2222
4. Copy the `writeKey` shown in the code block.
2323

24-
## Step 2: Add dependencies and initialization code
2524

26-
Next, add the Signals SDKs to your Swift applicatiion.
25+
## Prerequisites
2726

28-
1. Use Swift Package Manager to add the Signals SDK from the following repository:
27+
Auto-Instrumentation (aka Signals) works on top of Analytics. Make sure to add the following dependency to your project if you don't have analytics-swift already.
2928

30-
```zsh
31-
https://github.com/segment-integrations/analytics-swift-live.git
32-
```
29+
```swift
30+
dependencies: [
31+
.package(url: "https://github.com/segmentio/analytics-swift.git", from: "1.9.1")
32+
]
33+
```
3334

34-
2. Add the initialization code and configuration options:
35+
## Step 1: Getting started
36+
37+
1. Add AnalyticsLive to your Swift Package dependencies:
38+
```swift
39+
dependencies: [
40+
.package(url: "https://github.com/segmentio/analytics-live-swift.git", from: "3.2.1")
41+
]
42+
```
3543

44+
2. Import and initialize with your Analytics instance:
45+
3646
> success ""
3747
> See [configuration options](#configuration-options) for a complete list.
48+
>
49+
```swift
50+
import Segment
51+
import AnalyticsLive
52+
53+
let analytics = Analytics(configuration: Configuration(writeKey: "YOUR_WRITE_KEY"))
54+
55+
// Add LivePlugins first
56+
analytics.add(plugin: LivePlugins())
57+
58+
// Add Signals
59+
analytics.add(plugin: Signals.shared)
60+
61+
// Configure Signals
62+
Signals.shared.useConfiguration(SignalsConfiguration(
63+
writeKey: "YOUR_WRITE_KEY", // Same writeKey as Analytics
64+
useUIKitAutoSignal: true,
65+
useSwiftUIAutoSignal: true,
66+
useNetworkAutoSignal: true,
67+
#if DEBUG
68+
// NOTE: See section below on using these flags appropriately.
69+
sendDebugSignalsToSegment: true, // Only true for development
70+
obfuscateDebugSignals: false // Only false for development
71+
#endif
72+
// ... other options
73+
))
74+
```
75+
76+
3. Set up capture for the UI framework(s) you're using:
77+
* [Capture SwiftUI Interactions](#swiftui)
78+
* [Capture UIKit Interactions](#uikit)
79+
* [Capture Network Activity](#capture-network)
3880

81+
82+
## Step 2: Additional setup
83+
84+
### Capture Interactions
85+
86+
#### SwiftUI
87+
88+
SwiftUI automatic signal capture requires adding typealiases to your code. This is necessary because SwiftUI doesn't provide hooks for automatic instrumentation.
89+
90+
1. Enable SwiftUI auto-signals in your configuration:
3991
```swift
40-
// Configure Analytics with your settings
41-
{... <analytics config>....}
92+
Signals.shared.useConfiguration(SignalsConfiguration(
93+
writeKey: "YOUR_WRITE_KEY",
94+
useSwiftUIAutoSignal: true
95+
// ... other options
96+
))
97+
```
4298

43-
// Set up the Signals SDK configuration
44-
let config = Signals.Configuration(
45-
writeKey: "<WRITE_KEY>", // Replace <WRITE_KEY> with the write key you previously copied
46-
maximumBufferSize: 100,
47-
useSwiftUIAutoSignal: true,
48-
useNetworkAutoSignal: true
49-
)
99+
2. Add the following typealiases to your SwiftUI views or in a shared file:
100+
```swift
101+
import SwiftUI
102+
import AnalyticsLive
103+
104+
// Navigation
105+
typealias NavigationLink = SignalNavigationLink
106+
typealias NavigationStack = SignalNavigationStack // iOS 16+
107+
108+
// Selection & Input Controls
109+
typealias Button = SignalButton
110+
typealias TextField = SignalTextField
111+
typealias SecureField = SignalSecureField
112+
typealias Picker = SignalPicker
113+
typealias Toggle = SignalToggle
114+
typealias Slider = SignalSlider // Not available on tvOS
115+
typealias Stepper = SignalStepper // Not available on tvOS
116+
117+
// List & Collection Views
118+
typealias List = SignalList
119+
```
50120

51-
// Locate and set the fallback JavaScript file for edge functions
52-
let fallbackURL = Bundle.main.url(forResource: "MyEdgeFunctions", withExtension: "js")
121+
3. Use the controls normally in your SwiftUI code:
122+
```swift
123+
struct ContentView: View {
124+
var body: some View {
125+
NavigationStack {
126+
VStack {
127+
Button("Click Me") {
128+
// Button tap will automatically generate a signal
129+
}
130+
131+
TextField("Enter text", text: $text)
132+
// Text changes will automatically generate signals
133+
}
134+
}
135+
}
136+
}
137+
```
138+
139+
> **Note:** The typealiases replace SwiftUI's native controls with signal-generating versions. Your code remains unchanged, but interactions are now automatically captured.
140+
141+
#### UIKit
142+
143+
UIKit automatic signal capture uses method swizzling and requires no code changes.
53144

54-
// Apply the configuration and add the Signals plugin
55-
Signals.shared.useConfiguration(config)
56-
Analytics.main.add(plugin: LivePlugins(fallbackFileURL: fallbackURL))
57-
Analytics.main.add(plugin: Signals.shared)
145+
1. Enable UIKit auto-signals in your configuration:
146+
```swift
147+
Signals.shared.useConfiguration(SignalsConfiguration(
148+
writeKey: "YOUR_WRITE_KEY",
149+
useUIKitAutoSignal: true
150+
// ... other options
151+
))
58152
```
59153

60-
Verify that you replaced `<WRITE_KEY>` with the actual write key you copied in [Step 1](#step-1-get-your-source-write-key).
154+
2. That's it! The following UIKit interactions and navigation events are automatically captured via method swizzling:
155+
156+
**Interactions:**
157+
- `UIButton` taps
158+
- `UISlider` value changes
159+
- `UIStepper` value changes
160+
- `UISwitch` toggle events
161+
- `UITextField` text changes
162+
- `UITableViewCell` selections
163+
164+
**Navigation:**
165+
- `UINavigationController` push/pop operations
166+
- `UIViewController` modal presentations and dismissals
167+
- `UITabBarController` tab switches
168+
169+
### Capture Navigation
170+
171+
Navigation capture is handled automatically when you enable SwiftUI or UIKit auto-signals:
172+
173+
- **SwiftUI**: Captured through `SignalNavigationLink` and `SignalNavigationStack` when you add the typealiases
174+
- **UIKit**: Captured automatically via `UINavigationController`, `UIViewController`, and `UITabBarController` swizzling
61175

62-
#### SwiftUI projects
176+
No additional setup required beyond enabling the appropriate auto-signal flags.
63177

64-
If your app is written in SwiftUI, you need to add a `TypeAlias.swift` file to your project that captures interaction and navigation Signals, like in this example:
178+
### Capture Network
179+
180+
Network capture automatically tracks URLSession requests and responses.
181+
182+
1. Enable network auto-signals in your configuration:
183+
```swift
184+
Signals.shared.useConfiguration(SignalsConfiguration(
185+
writeKey: "YOUR_WRITE_KEY",
186+
useNetworkAutoSignal: true,
187+
allowedNetworkHosts: ["*"], // Allow all hosts (default)
188+
blockedNetworkHosts: [] // Block specific hosts (optional)
189+
// ... other options
190+
))
191+
```
192+
193+
2. Network requests made via URLSession are automatically captured, including:
194+
- Request URL, method, headers, and body
195+
- Response status, headers, and body
196+
- Request/response correlation via request ID
197+
198+
> **Note:** Third-party networking libraries that use URLSession underneath (like Alamofire) should work automatically. Segment API endpoints are automatically blocked to prevent recursive tracking.
199+
200+
#### Configuring Network Hosts
201+
202+
You can control which network requests are tracked:
65203

66204
```swift
67-
import Foundation
68-
import Signals
69-
70-
typealias Button = SignalButton
71-
typealias NavigationStack = SignalNavigationStack
72-
typealias NavigationLink = SignalNavigationLink
73-
typealias TextField = SignalTextField
74-
typealias SecureField = SignalSecureField
205+
SignalsConfiguration(
206+
writeKey: "YOUR_WRITE_KEY",
207+
useNetworkAutoSignal: true,
208+
allowedNetworkHosts: ["api.myapp.com", "*.example.com"], // Only track these hosts
209+
blockedNetworkHosts: ["analytics.google.com"] // Exclude these hosts
210+
)
75211
```
76212

77-
## Step 3: Turn on Auto-Instrumentation in your source
213+
- `allowedNetworkHosts`: Array of host patterns to track. Use `"*"` to allow all hosts (default).
214+
- `blockedNetworkHosts`: Array of host patterns to exclude from tracking.
215+
216+
The following hosts are automatically blocked to prevent recursive tracking:
217+
- `api.segment.com`
218+
- `cdn-settings.segment.com`
219+
- `signals.segment.com`
220+
- `api.segment.build`
221+
- `cdn.segment.build`
222+
- `signals.segment.build`
223+
224+
## Step 3: Enable debug mode
225+
226+
By default, Signals stores captured data on the device and doesn't forward it to Segment. This process prevents unnecessary bandwidth use and helps support privacy compliance requirements.
227+
228+
To view captured signals in the Event Builder and create event generation rules, you need to enable `sendDebugSignalsToSegment`. This setting temporarily lets the SDK send signal data to Segment while you're testing.
229+
230+
In addition, the SDK obfuscates signals sent to Segment by default. To view the completed data, you need to turn off `obfuscateDebugSignals`.
231+
232+
> warning ""
233+
> Only enable `sendDebugSignalsToSegment` in development environments. Avoid using `sendDebugSignalsToSegment` in production apps.
234+
235+
You can enable `sendDebugSignalsToSegment` and turn off `obfuscateDebugSignals` in one of three ways.
236+
237+
### Option 1: Use Build Configurations to Toggle Debug Mode
238+
239+
1. Define different configurations in your project settings (Debug, Release, etc.)
240+
241+
2. Use compiler flags to control the setting:
242+
```swift
243+
Signals.shared.useConfiguration(SignalsConfiguration(
244+
writeKey: "YOUR_WRITE_KEY",
245+
// ... other config options
246+
#if DEBUG
247+
sendDebugSignalsToSegment: true,
248+
obfuscateDebugSignals: false
249+
#else
250+
sendDebugSignalsToSegment: false,
251+
obfuscateDebugSignals: true
252+
#endif
253+
))
254+
```
255+
256+
### Option 2: Use a Feature Flag System
257+
If you're using Firebase Remote Config or a similar feature flag system, you can dynamically control `sendDebugSignalsToSegment` and `obfuscateDebugSignals` without requiring a new app build:
258+
```swift
259+
let remoteConfig = RemoteConfig.remoteConfig()
260+
261+
Signals.shared.useConfiguration(SignalsConfiguration(
262+
writeKey: "YOUR_WRITE_KEY",
263+
// ... other config options
264+
sendDebugSignalsToSegment: remoteConfig["sendDebugSignalsToSegment"].boolValue,
265+
obfuscateDebugSignals: remoteConfig["obfuscateDebugSignals"].boolValue
266+
))
267+
```
268+
269+
### Option 3: Use Environment Variables (for debugging/testing)
270+
You can check for environment variables or launch arguments during development:
271+
```swift
272+
let isDebugEnabled = ProcessInfo.processInfo.environment["SIGNALS_DEBUG"] != nil
273+
274+
Signals.shared.useConfiguration(SignalsConfiguration(
275+
writeKey: "YOUR_WRITE_KEY",
276+
// ... other config options
277+
sendDebugSignalsToSegment: isDebugEnabled,
278+
obfuscateDebugSignals: !isDebugEnabled
279+
))
280+
```
281+
282+
## Step 4: Turn on Auto-Instrumentation in your source
78283

79284
Next, return to the source settings to turn on Auto-Instrumentation:
80285

@@ -83,34 +288,38 @@ Next, return to the source settings to turn on Auto-Instrumentation:
83288
3. From the source's overview tab, go to **Settings > Advanced**.
84289
4. Toggle Auto-Instrumention on.
85290

86-
## Step 4: Verify and deploy events
291+
## Step 5: Verify and deploy events
87292

88293
After integrating the SDK and running your app, verify that Segment is collecting signals:
89294

90295
1. In your Segment workspace, go to **Connections > Sources** and select the source you used for Auto-Instrumentation.
91296
2. In the source overview, look for the **Event Builder** tab. If the tab doesn’t appear:
92297
- Make sure you've installed the SDK correctly.
93298
- Reach out to your Segment CSM to confirm that your workspace has the necessary feature flags enabled.
94-
3. Launch your app [in debug mode](https://github.com/segmentio/analytics-next/tree/master/packages/signals/signals#sending-and-viewing-signals-on-segmentcom-debug-mode){:target="_blank"}. This enables signal collection so you can see activity in the Event Builder.
299+
3. If `sendDebugSignalsToSegment` is enabled, Signals appear in real time in the Event Builder as you interact with the app.
95300
4. Use the app as a user would: navigate between screens, tap buttons, trigger network requests. Signals appear in real time as you interact with the app.
96301
5. In the Event Builder, find a signal and click **Configure event** to define a new event. After configuring the event, click **Publish event rules**.
97302

98303
## Configuration options
99304

100305
Using the Signals Configuration object, you can control the destination, frequency, and types of signals that Segment automatically tracks within your application. The following table details the configuration options for Signals-Swift.
101306

102-
| `Option` | Required | Value | Description |
103-
| ---------------------- | -------- | -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
104-
| `writeKey` | Yes | String | Source write key |
105-
| `maximumBufferSize` | No | Integer | The number of signals to be kept for JavaScript inspection. This buffer is first-in, first-out. Default is `1000`. |
106-
| `relayCount` | No | Integer | Relays signals to Segment every Xth event. Default is `20`. |
107-
| `relayInterval` | No | TimeInterval | Relays signals to segment every X seconds. Default is `60`. |
108-
| `broadcasters` | No | `SignalBroadcaster` | An array of broadcasters. These objects forward signal data to their destinations, like `WebhookBroadcaster` or `DebugBroadcaster` writing to the developer console. Default is `SegmentBroadcaster`. |
109-
| `useUIKitAutoSignal` | No | Bool | Tracks UIKit component interactions automatically. Default is `false`. |
110-
| `useSwiftUIAutoSignal` | No | Bool | Tracks SwiftUI component interactions automatically. Default is `false`. |
111-
| `useNetworkAutoSignal` | No | Bool | Tracks network events automatically. Default is `false`. |
112-
| `allowedNetworkHosts` | No | Array | An array of allowed network hosts. |
113-
| `blockedNetworkHosts` | No | Array | An array of blocked network hosts.
307+
308+
| OPTION | REQUIRED | VALUE | DESCRIPTION |
309+
|------------------|----------|---------------------------|-------------|
310+
| **writeKey** | Yes | String | Your Segment write key. Should match your Analytics instance writeKey. |
311+
| **maximumBufferSize** | No | Int | The number of signals to be kept for JavaScript inspection. This buffer is first-in, first-out. Default is **1000**. |
312+
| **relayCount** | No | Int | Relays every X signals to Segment. Default is **20**. |
313+
| **relayInterval** | No | TimeInterval | Relays signals to Segment every X seconds. Default is **60**. |
314+
| **broadcasters** | No | [SignalBroadcaster] | An array of broadcasters. These objects forward signal data to their destinations, like **WebhookBroadcaster**, or you could write your own **DebugBroadcaster** that writes logs to the developer console. **SegmentBroadcaster** is always added by the SDK when `sendDebugSignalsToSegment` is true. |
315+
| **sendDebugSignalsToSegment** | No | Bool | Turns on debug mode and allows the SDK to relay Signals to Segment server. Default is **false**. It should only be set to true for development purposes. |
316+
| **obfuscateDebugSignals** | No | Bool | Obfuscates signals being relayed to Segment. Default is **true**. |
317+
| **apiHost** | No | String | API host for signal relay. Default is **"signals.segment.io/v1"**. |
318+
| **useUIKitAutoSignal** | No | Bool | Enables automatic UIKit signal capture via method swizzling. Default is **false**. |
319+
| **useSwiftUIAutoSignal** | No | Bool | Enables automatic SwiftUI signal capture (requires typealiases). Default is **false**. |
320+
| **useNetworkAutoSignal** | No | Bool | Enables automatic network signal capture for URLSession. Default is **false**. |
321+
| **allowedNetworkHosts** | No | [String] | Array of host patterns to track. Use `["*"]` for all hosts. Default is **["*"]**. |
322+
| **blockedNetworkHosts** | No | [String] | Array of host patterns to exclude from tracking. Default is **[]**. |
114323

115324
## Next steps
116325

0 commit comments

Comments
 (0)