Include the Swift Client in your Xcode Project
See the Article Setting up your App on how to set up your app to use the Telemetry Swift Client.
Initialization
Init the Telemetry Manager at app startup, so it knows your App ID (you can retrieve the App ID in the Telemetry Viewer app, under App Settings)
let configuration = TelemetryManagerConfiguration(appID: "<YOUR-APP-ID>")
TelemetryManager.initialize(with: configuration)
For example, if you're building a scene based app, in the init()
function for your App
:
import SwiftUI
import TelemetryClient
@main
struct TelemetryTestApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
}
init() {
// Note: Do not add this code to `WindowGroup.onAppear`, which will be called
// *after* your window has been initialized, and might lead to out initialization
// occurring too late.
let configuration = TelemetryManagerConfiguration(appID: "<YOUR-APP-ID>")
TelemetryManager.initialize(with: configuration)
}
}
Sending Signals
Once you've included the Telemetry Swift Client, send signals like so:
TelemetryManager.send("appLaunchedRegularly")
Telemetry Manager will create a user identifier for you user that is specific to app installation and device. If you have a better user identifier available, you can use that instead: (the identifier will be hashed before sending it)
let email = MyConfiguration.User.Email
TelemetryManager.send("userLoggedIn", for: email)
Note on User Identifiers on Mac
If you are writing a Mac App, Telemetry Manager can not create a unique user identifer, and will instead default to a concatenation of your OS Version and App Build number, which is not exactly unique, so user counting will be less accurate.
I therefore strongly recommend to either use a unique identifier for your users, such as an email address, or to generate and store a `UUID().uuidString`, for example in `UserDefaults`, and always pass that to Telemetry Manager as User ID.
The reason why Telemetry Manager can't do that itself is that it feels like crossing a line if this very simple tool would generate IDs itself and write those to a directory on disk. I feel that this is not expected behaviour for a privacy-first analaytics package.
Payload Data
You can also send additional payload data with each signal:
TelemetryManager.send("databaseUpdated", with: ["numberOfDatabaseEntries": "3831"])
Telemetry Manager will automatically send a base payload with these keys:
- platform
- systemVersion
- appVersion
- buildNumber
- isSimulator
- isTestFlight
- isAppStore
- modelName
- architecture
- operatingSystem
- targetEnvironment
Debug Mode
Telemetry Manager will not send any signals if you are in DEBUG
Mode. You can override this by setting configuration.telemetryAllowDebugBuilds = true
on your TelemetryManagerConfiguration
instance.