iOS (Swift) SDK
iOS
MetaRouter iOS SDK
The MetaRouter iOS SDK enables you to capture analytics events directly from your app and route them through the MetaRouter platform to your configured downstream integrations.
Built for performance, the SDK uses an internal queue to ensure all tracking calls are non-blocking and efficient. Events are batched and sent asynchronously to avoid impacting app performance.
MetaRouter ios-sdk on GitHub
Installation Instructions
-
Install MetaRouter SDK:
Add the MetaRouter SDK to your project using Swift Package Manager. In Xcode, go to
File > Swift Packages > Add Package Dependencyand enter the repository URL. -
Initialize the Analytics Client:
This is the minimum configuration required to use the analytics package within the MetaRouter SDK:
import MetaRouter let client = AnalyticsClient.initialize(options: InitOptions(writeKey: "your-write-key", ingestionHost: "https://your-ingestion-host.com", debug: false))writeKey: Identifies the MetaRouter pipeline.ingestionHost: Base URL of your MetaRouter ingestion infrastructure.flushInterval: Flushes queued events every N seconds optional( default is 10).debug: Enables verbose debug logging optional (default is false)
Usage
Event Tracking
Track custom user actions, screen views, and more:
// Track a custom event
client.track("event_name", properties: ["key": "value"])
// Track a screen view
client.screen("screen_name", properties: ["key": "value"])
// Track a page view (web semantics)
client.page("page_name", properties: ["key": "value"])User Identity
Associate traits with a known user:
// Identify a user
client.identify(userId: "user_id", traits: ["key": "value"])
// Alias user IDs
client.alias(newUserId: "new_user_id")
// Group users
client.group(groupId: "group_id", traits: ["key": "value"])Lifecycle & Utilities
Manage the analytics client lifecycle and utilities:
// Flush events immediately
client.flush()
// Reset analytics state and clear all stored data
client.reset()
// Enable debug logging
client.enableDebugLogging()
// Get current debug information
let debugInfo = await client.getDebugInfo()Advertising Identifier
Set and manage the advertising identifier (IDFA) for ad tracking and attribution:
// Set advertising ID (IDFA) for ad tracking
// The ID is persisted and automatically restored on app launch
client.setAdvertisingId("your-advertising-id")
// Clear advertising ID (for GDPR compliance)
// Removes IDFA from future events while preserving user and anonymous IDs
client.clearAdvertisingId()Note: The advertising ID requires proper App Tracking Transparency (ATT) authorization on iOS 14.5+. You must request user permission before collecting IDFA and handle consent in compliance with privacy regulations (GDPR, CCPA). The advertising ID is also cleared when calling reset().
Event Queueing and Batch Processing
The MetaRouter iOS SDK is designed to efficiently handle event tracking through an internal queue and batch processing system. Here's how it works:
Event Queueing: Events are queued in memory before being sent to the server. This ensures that tracking calls are non-blocking and do not impact app performance.
Batch Sizes: Events are sent in batches to optimize network usage. The default batch size is configured to balance between network efficiency and timely event delivery.
In-Memory Queue: The SDK maintains an in-memory queue with a default capacity of 2,000 events. If the queue reaches its capacity, the oldest events are dropped to make room for new ones.
Network Failures: In case of network failures, the SDK employs a retry mechanism with exponential backoff. Events that fail to send due to non-retryable errors (e.g., client misconfiguration) are dropped.
Process Termination: Events in the queue are not persisted to disk. If the app is terminated before events are flushed, those events will be lost.
Flush Interval: The SDK automatically flushes the event queue at regular intervals, which can be configured via the flushIntervalSeconds option. You can also manually flush the queue using the flush() method.
Circuit Breaker: The SDK includes a circuit breaker mechanism to handle repeated network failures gracefully, preventing excessive retries and allowing the system to recover smoothly.
This design ensures that the SDK can handle high volumes of events efficiently while minimizing the risk of data loss.
Example
Here's a simple example of how to integrate the MetaRouter SDK into your iOS app:
import UIKit
import MetaRouter
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var client: AnalyticsClient!
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Initialize the analytics client
client = AnalyticsClient.initialize(options: InitOptions(writeKey: "your-write-key", ingestionHost: "https://your-ingestion-host.com", debug: true))
// Note: The AnalyticsClient can be used as a singleton or assigned to a variable.
// Both approaches will use the same instance under the hood.
return true
}
}Updated 10 days ago