Datablit Swift SDK
A Swift library for tracking analytics events and user identification with Datablit. The SDK provides easy integration with iOS and macOS applications, featuring automatic batching, lifecycle event tracking, rule evaluation, and experiment variant retrieval.
Installation
Swift Package Manager
Add the following dependency to your Package.swift
:
dependencies: [
.package(url: "https://github.com/datablit/datablit-swift.git", from: "1.0.0")
]
Or add it directly in Xcode:
- Go to File → Add Package Dependencies
- Enter the repository URL:
https://github.com/datablit/datablit-swift
- Select the version you want to use
Quick Start
Here's how to get started with the Datablit Swift SDK:
import Datablit
// Initialize the SDK
Datablit.shared.initialize(apiKey: "your-api-key-here")
// Track an event
Datablit.shared.track(eventName: "Button Clicked", properties: ["buttonId": "signup-button"])
// Identify a user
Datablit.shared.identify(userId: "user123", traits: ["email": "user@example.com", "plan": "premium"])
API Reference
Datablit.shared.initialize(config)
Initializes the Datablit SDK. You should initialize this library once before using any other functions.
Parameters:
Parameter | Type | Required | Description |
---|---|---|---|
apiKey | String | Yes | Your Datablit API key. Get this from the Datablit project source Create new project/source if its not created yet |
endpoint | String | No | Custom endpoint URL for analytics data. Default: https://event.datablit.com/v1/batch |
flushAt | Int | No | Number of events to batch before sending. Default: 20 |
flushInterval | TimeInterval | No | Seconds between automatic flushes. Default: 30.0 |
trackApplicationLifecycleEvents | Bool | No | Whether to track app lifecycle events. Default: false |
enableDebugLogs | Bool | No | Whether to enable debug logging. Default: false |
Analytics API
Datablit.shared.identify(userId, traits)
Identifies a user with optional traits.
Parameters:
Parameter | Type | Required | Description |
---|---|---|---|
userId | String | Yes | Unique identifier for the user |
traits | Dictionary or Codable | No | User traits and properties |
Example:
// Using dictionary
Datablit.shared.identify(userId: "user_123", traits: [
"name": "John Doe",
"email": "john.doe@example.com",
"plan": "premium"
])
// Using Codable struct
struct UserTraits: Codable {
let name: String
let email: String
let plan: String
let signupDate: Date
}
let traits = UserTraits(
name: "John Doe",
email: "john.doe@example.com",
plan: "premium",
signupDate: Date()
)
Datablit.shared.identify(userId: "user_123", traits: traits)
Datablit.shared.track(eventName, properties)
Tracks an event with associated properties.
Parameters:
Parameter | Type | Required | Description |
---|---|---|---|
eventName | String | Yes | Name of the event |
properties | Dictionary or Codable | No | Key-value pairs of event properties |
Example:
// Simple event tracking
Datablit.shared.track(eventName: "Button Clicked", properties: ["button": "subscribe", "user": "user_123"])
// More complex example
Datablit.shared.track(eventName: "Purchase Completed", properties: [
"productId": "prod_123",
"amount": 99.99,
"currency": "USD"
])
// Using Codable struct
struct PurchaseEvent: Codable {
let productId: String
let amount: Double
let currency: String
}
let purchaseEvent = PurchaseEvent(
productId: "prod_123",
amount: 99.99,
currency: "USD"
)
Datablit.shared.track(eventName: "Purchase Completed", properties: purchaseEvent)
Rules API
Rule.evalRule(key, userId, params)
Evaluates a rule for a given user and context. This allows you to make dynamic decisions based on user attributes and rule logic.
Parameters:
Parameter | Type | Required | Description |
---|---|---|---|
key | String | Yes | The rule key identifier |
userId | String | Yes | Unique user ID |
params | Dictionary | No | Additional parameters for rule evaluation |
Returns:
EvalRuleResponse
withresult
(Bool) indicating whether the rule passed.
Example:
let rule = Rule(apiKey: "your-api-key")
let response = await rule.evalRule(
key: "feature_flag",
userId: "user_123",
params: [
"os_name": "iOS",
"user_plan": "premium"
]
)
if response.result {
print("Rule evaluated to true - show feature")
} else {
print("Rule evaluated to false - hide feature")
}
Experiments API
Experiment.getVariant(expId, entityId)
Retrieves the experiment variant for a user. This is useful for A/B testing and feature experimentation.
Parameters:
Parameter | Type | Required | Description |
---|---|---|---|
expId | String | Yes | The experiment ID |
entityId | String | Yes | Unique entity/user ID |
Returns:
GetVariantResponse
withvariant
(String) indicating the assigned variant.
Example:
let experiment = Experiment(apiKey: "your-api-key")
let response = await experiment.getVariant(
expId: "01K2JKVXR0J0ZWPX40XY8CAWBS",
entityId: "user_123"
)
print("User is in variant: \(response.variant)") // "control", "variant_a", etc.
// Use the variant to show different UI
if response.variant == "variant_a" {
// Show new feature
} else {
// Show control version
}
Auto-Tracked Events
If trackApplicationLifecycleEvents
is enabled, the SDK will automatically track:
Application Launched
Application Active
Application Foreground
Application Backgrounded
These include rich contextual data such as device and app info, locale, and network type.
Error Handling
The SDK provides comprehensive error handling mechanisms:
// Rule evaluation and experiments use try-catch for async operations
do {
let rule = Rule(apiKey: "your-api-key")
let ruleResponse = try await rule.evalRule(key: "feature_flag", userId: "user_123")
let experiment = Experiment(apiKey: "your-api-key")
let variantResponse = try await experiment.getVariant(expId: "exp_123", entityId: "user_123")
// Use results safely
if ruleResponse.result {
print("Feature enabled, variant: \(variantResponse.variant)")
}
} catch {
print("API call failed: \(error.localizedDescription)")
}
// Analytics methods handle errors gracefully - no try-catch needed
Datablit.shared.track(eventName: "Event", properties: ["data": "value"])
Debug Logging
Enable debug logging during development to troubleshoot issues:
Datablit.shared.initialize(
apiKey: "your-api-key",
enableDebugLogs: true // Shows network requests and status codes
)
- Error Messages (❌): Always logged, regardless of debug setting
- Debug Messages (✅): Only logged when
enableDebugLogs
istrue
Features
-
Analytics:
- Event Tracking: Monitor user interactions and custom events
- User Identification: Link events to specific users
- Automatic Lifecycle Tracking: Capture app lifecycle events automatically
- Batch Processing: Efficiently batch events with retry logic
- Thread Safety: Built with concurrency safety in mind
- Network Monitoring: Automatic network status detection
-
Rules:
- Rule Evaluation: Assess rules against user context in real-time
- Context-based Decisions: Make dynamic decisions based on user attributes
- Feature Flags: Control feature rollouts dynamically
-
Experiments:
- A/B Testing: Retrieve experiment variants for users
- Context-aware Assignment: Assign variants based on user context
- Statistical Analysis: Built-in support for experiment analysis
-
Developer Experience:
- Swift Package Manager support
- Comprehensive error handling
- Debug logging for troubleshooting
- Full Swift type safety with Codable support
- iOS and macOS compatibility
Event Context
Each event includes contextual data like:
- Device (model, manufacturer, type)
- Screen (dimensions)
- App (version, build, bundle ID)
- OS (name and version)
- Locale and timezone
- Network type (WiFi, Cellular)
- User agent
Complete Example
Here's a comprehensive example showing how to use all aspects of the Datablit Swift SDK:
import Datablit
class AnalyticsManager {
static let shared = AnalyticsManager()
private let rule: Rule
private let experiment: Experiment
private init() {
// Initialize analytics
Datablit.shared.initialize(
apiKey: "your-api-key-here",
trackApplicationLifecycleEvents: true,
enableDebugLogs: true
)
// Initialize rule and experiment engines
rule = Rule(apiKey: "your-api-key-here")
experiment = Experiment(apiKey: "your-api-key-here")
}
func identifyUser(userId: String, email: String, plan: String) {
Datablit.shared.identify(userId: userId, traits: [
"email": email,
"plan": plan,
"signupDate": Date()
])
}
func trackPurchase(userId: String, productId: String, amount: Double) {
Datablit.shared.track(eventName: "Purchase Completed", properties: [
"userId": userId,
"productId": productId,
"amount": amount,
"currency": "USD"
])
}
func checkFeatureFlag(userId: String) async -> Bool {
do {
let response = try await rule.evalRule(
key: "premium_feature_enabled",
userId: userId,
params: ["platform": "iOS"]
)
return response.result
} catch {
print("Failed to evaluate feature flag: \(error)")
return false // Default to disabled
}
}
func getExperimentVariant(userId: String) async -> String {
do {
let response = try await experiment.getVariant(
expId: "checkout_flow_experiment",
entityId: userId
)
return response.variant
} catch {
print("Failed to get experiment variant: \(error)")
return "control" // Default to control
}
}
}
// Usage in your app
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Identify user
AnalyticsManager.shared.identifyUser(
userId: "user_123",
email: "user@example.com",
plan: "premium"
)
// Check feature flag
Task {
let isFeatureEnabled = await AnalyticsManager.shared.checkFeatureFlag(userId: "user_123")
if isFeatureEnabled {
// Show premium feature
showPremiumFeature()
}
// Get experiment variant
let variant = await AnalyticsManager.shared.getExperimentVariant(userId: "user_123")
switch variant {
case "variant_a":
setupVariantAUI()
case "variant_b":
setupVariantBUI()
default:
setupControlUI()
}
}
}
@IBAction func purchaseButtonTapped(_ sender: UIButton) {
AnalyticsManager.shared.trackPurchase(
userId: "user_123",
productId: "premium_plan",
amount: 99.99
)
}
}
Usage in SwiftUI
Here's how to use the Datablit SDK in a SwiftUI application:
import SwiftUI
import Datablit
@main
struct MyApp: App {
init() {
// Initialize Datablit SDK
Datablit.shared.initialize(
apiKey: "your-api-key-here",
trackApplicationLifecycleEvents: true
)
}
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
struct ContentView: View {
@State private var isFeatureEnabled = false
var body: some View {
VStack(spacing: 20) {
if isFeatureEnabled {
Text("Premium Feature Enabled!")
.foregroundColor(.blue)
}
Button("Track Event") {
Datablit.shared.track(eventName: "Button Clicked", properties: [
"screen": "home",
"button": "track_event"
])
}
Button("Identify User") {
Datablit.shared.identify(userId: "user_123", traits: [
"name": "John Doe",
"email": "john@example.com"
])
}
}
.onAppear {
Task {
await checkFeatureFlag()
}
}
}
private func checkFeatureFlag() async {
let rule = Rule(apiKey: "your-api-key-here")
do {
let response = try await rule.evalRule(key: "premium_feature", userId: "user_123")
isFeatureEnabled = response.result
} catch {
print("Failed to check feature flag: \(error)")
}
}
}
For more information and examples, visit the Datablit Swift SDK GitHub repository.