CocoaPods trunk is moving to be read-only. Read more on the blog, there are 12 months to go.

MostlyGoodMetrics 0.1.0

MostlyGoodMetrics 0.1.0

Maintained by Josh Holtz.



  • By
  • Josh Holtz

MostlyGoodMetrics Swift SDK

A lightweight Swift SDK for tracking analytics events with MostlyGoodMetrics.

Requirements

  • iOS 14.0+ / macOS 11.0+ / tvOS 14.0+ / watchOS 7.0+
  • Swift 5.9+

Installation

Swift Package Manager

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.

Quick Start

1. Initialize the SDK

Initialize once at app launch (e.g., in AppDelegate or @main App struct):

import MostlyGoodMetrics

MostlyGoodMetrics.configure(apiKey: "mgm_proj_your_api_key")

2. Track Events

// Simple event
MostlyGoodMetrics.track("button_clicked")

// Event with properties
MostlyGoodMetrics.track("purchase_completed", properties: [
    "product_id": "SKU123",
    "price": 29.99,
    "currency": "USD"
])

3. Identify Users

// 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.

Configuration Options

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

Automatic 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) -

Automatic Context

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 Naming

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 space

Properties

Events 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

Manual Flush

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)")
    }
}

Automatic Behavior

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-After headers
  • Persists user ID across app launches
  • Generates session IDs per app launch

Debug Logging

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

Thread Safety

The SDK is fully thread-safe. You can call track() from any thread.

License

MIT