A lightweight Swift SDK for tracking analytics events with MostlyGoodMetrics.
- iOS 14.0+ / macOS 11.0+ / tvOS 14.0+ / watchOS 7.0+
- Swift 5.9+
Add the following to your Package.swift:
dependencies: [
.package(url: "https://github.com/Mostly-Good-Metrics/mostly-good-metrics-swift-sdk", from: "1.0.0")
]Or in Xcode: File > Add Package Dependencies and enter the repository URL.
Initialize once at app launch (e.g., in AppDelegate or @main App struct):
import MostlyGoodMetrics
MostlyGoodMetrics.configure(apiKey: "mgm_proj_your_api_key")// Simple event
MostlyGoodMetrics.track("button_clicked")
// Event with properties
MostlyGoodMetrics.track("purchase_completed", properties: [
"product_id": "SKU123",
"price": 29.99,
"currency": "USD"
])// Set user identity
MostlyGoodMetrics.identify(userId: "user_123")
// Reset identity (e.g., on logout)
MostlyGoodMetrics.shared?.resetIdentity()That's it! Events are automatically batched and sent.
For more control, use MGMConfiguration:
let config = MGMConfiguration(
apiKey: "mgm_proj_your_api_key",
baseURL: URL(string: "https://mostlygoodmetrics.com")!,
environment: "production",
maxBatchSize: 100,
flushInterval: 30,
maxStoredEvents: 10000,
enableDebugLogging: false,
trackAppLifecycleEvents: true
)
MostlyGoodMetrics.configure(with: config)| Option | Default | Description |
|---|---|---|
apiKey |
Required | Your API key |
baseURL |
https://mostlygoodmetrics.com |
API endpoint |
environment |
"production" |
Environment name |
bundleId |
App's bundle ID | Override bundle identifier |
maxBatchSize |
100 |
Events per batch (1-1000) |
flushInterval |
30 |
Auto-flush interval in seconds |
maxStoredEvents |
10000 |
Max cached events |
enableDebugLogging |
false |
Enable console output |
trackAppLifecycleEvents |
true |
Auto-track lifecycle events |
When trackAppLifecycleEvents is enabled (default), the SDK automatically tracks:
| Event | When | Properties |
|---|---|---|
$app_installed |
First launch after install | $version |
$app_updated |
First launch after version change | $version, $previous_version |
$app_opened |
App became active (foreground) | - |
$app_backgrounded |
App resigned active (background) | - |
Every event automatically includes:
| Field | Example | Description |
|---|---|---|
platform |
"ios" |
Platform (ios, macos, tvos, watchos, visionos) |
os_version |
"17.1" |
Operating system version |
app_version |
"1.0.0 (42)" |
App version with build number |
environment |
"production" |
Environment from configuration |
session_id |
"uuid..." |
Unique session ID (per app launch) |
user_id |
"user_123" |
User ID (if set via identify()) |
$device_type |
"phone" |
Device type (phone, tablet, desktop, tv, watch, vision) |
$device_model |
"iPhone15,2" |
Device model identifier |
Note: The
$prefix indicates reserved system events and properties. Avoid using$prefix for your own custom events.
Event names must:
- Start with a letter (or
$for system events) - Contain only alphanumeric characters and underscores
- Be 255 characters or less
// Valid
MostlyGoodMetrics.track("button_clicked")
MostlyGoodMetrics.track("PurchaseCompleted")
MostlyGoodMetrics.track("step_1_completed")
// Invalid (will be ignored)
MostlyGoodMetrics.track("123_event") // starts with number
MostlyGoodMetrics.track("event-name") // contains hyphen
MostlyGoodMetrics.track("event name") // contains spaceEvents support various property types:
MostlyGoodMetrics.track("checkout", properties: [
"string_prop": "value",
"int_prop": 42,
"double_prop": 3.14,
"bool_prop": true,
"list_prop": ["a", "b", "c"],
"nested": [
"key": "value"
]
])Limits:
- String values: truncated to 1000 characters
- Nesting depth: max 3 levels
- Total properties size: max 10KB
Events are automatically flushed periodically and when the app backgrounds. You can also trigger a manual flush:
MostlyGoodMetrics.shared?.flush { result in
switch result {
case .success:
print("Events flushed successfully")
case .failure(let error):
print("Flush failed: \(error.localizedDescription)")
}
}The SDK automatically:
- Persists events to disk, surviving app restarts
- Batches events for efficient network usage
- Flushes on interval (default: every 30 seconds)
- Flushes on background when the app resigns active
- Retries on failure for network errors (events are preserved)
- Compresses payloads using gzip for requests > 1KB
- Handles rate limiting by respecting
Retry-Afterheaders - Persists user ID across app launches
- Generates session IDs per app launch
Enable debug logging to see SDK activity:
let config = MGMConfiguration(
apiKey: "mgm_proj_your_api_key",
enableDebugLogging: true
)
MostlyGoodMetrics.configure(with: config)Output example:
[MostlyGoodMetrics] Initialized with 3 cached events
[MostlyGoodMetrics] Tracked event: button_clicked
[MostlyGoodMetrics] Flushing 4 events
[MostlyGoodMetrics] Successfully flushed 4 events
The SDK is fully thread-safe. You can call track() from any thread.
MIT