# iOS SDK Integration Guide

Source: https://appfig.com/docs/ios-integration

Complete guide to integrating AppFig into your iOS application.

## Installation

> **SDK Download Repository:** [https://github.com/smartconfigui/AppFig-SDKs](https://github.com/smartconfigui/AppFig-SDKs)

**Requirements:** iOS 12.0+, Xcode 13+, Swift 5.0+

### Swift Package Manager (recommended)

1. In Xcode: **File > Add Package Dependencies**
2. Enter the URL:
   ```
   https://github.com/smartconfigui/AppFig-SDKs
   ```
3. Choose version `2.5.0` or later and add the **AppFigSDK** library to your app target.

### CocoaPods

Add to your `Podfile`, then run `pod install`:

```ruby
pod 'AppFigSDK', :git => 'https://github.com/smartconfigui/AppFig-SDKs.git', :tag => 'v2.5.0'
```

### By hand

Download `ios/AppFigSDK.xcframework` from the
[SDK repository](https://github.com/smartconfigui/AppFig-SDKs/tree/v2.5.0/ios), drag it into your Xcode project
("Copy items if needed"), and under your app target's **General > Frameworks, Libraries, and Embedded Content**
set it to **Embed & Sign**.

### Import in your code

```swift
import AppFigSDK
```

**Note:** No external dependencies required. The XCFramework is self-contained.

## Quick Start

### Initialize

```swift
import UIKit

@main
class AppDelegate: UIResponder, UIApplicationDelegate {

    func application(_ application: UIApplication,
                    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

        // Initialize AppFig with auto-refresh
        AppFig.initialize(
            companyId: "your-company-id",
            tenantId: "your-tenant-id",
            env: "prod",
            apiKey: "your-api-key",
            autoRefresh: true,
            pollInterval: 3600000  // 1 hour
        )

        // Log events
        AppFig.logEvent(name: "app_open")

        // Check features
        if AppFig.isFeatureEnabled("double_xp") {
            applyDoubleXP()
        }

        if let maxLives = AppFig.getFeatureValue("max_lives") {
            playerLives = Int(maxLives) ?? 3
        }

        return true
    }
}
```

## When to Do What: Timing Guide

Understanding WHEN to call each SDK method is crucial for proper iOS integration:

| Action | When to Call | Where to Place | Code Example |
|--------|-------------|----------------|--------------|
| **Initialize SDK** | Once at app launch | `didFinishLaunchingWithOptions` | `AppFig.initialize(...)` |
| **Log Events** | Immediately after user action | IBAction methods, delegates | `AppFig.logEvent(name: "button_tap")` |
| **Set User Properties** | Once at login, when value changes | Auth callback, state change | `AppFig.setUserProperty(key: "tier", value: "premium")` |
| **Evaluate Features** | Right before you need the value | viewDidLoad, viewWillAppear | `AppFig.getFeatureValue("max_lives")` |
| **Apply Features** | Immediately after evaluation | Same method as evaluation | `if enabled { showUI() }` |
| **Refresh Rules** | On demand (auto-refresh handles this) | Manual: Settings screen | `AppFig.refreshRules()` |

### Complete Lifecycle Example

```swift
import UIKit

@main
class AppDelegate: UIResponder, UIApplicationDelegate {
    func application(_ application: UIApplication,
                     didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

        // 1. INITIALIZE: Once at app launch
        AppFig.initialize(
            companyId: "your-company-id",
            tenantId: "your-tenant-id",
            env: "prod",
            apiKey: "your-api-key"
        )

        // 2. TRACK: Log app open event
        AppFig.logEvent(name: "app_open")

        return true
    }
}

class MainViewController: UIViewController {
    @IBOutlet weak var welcomePanel: UIView!
    @IBOutlet weak var livesLabel: UILabel!
    private var playerLives = 3

    override func viewDidLoad() {
        super.viewDidLoad()

        // 3. EVALUATE: Check features when view loads
        checkWelcomeBonus()
        configureGameSettings()
    }

    func checkWelcomeBonus() {
        // Evaluate right before using
        if AppFig.isFeatureEnabled("welcome_bonus") {
            // 4. APPLY: Show bonus immediately
            welcomePanel.isHidden = false
            grantBonus(coins: 500)
        } else {
            welcomePanel.isHidden = true
        }
    }

    func configureGameSettings() {
        // Evaluate with fallback
        if let maxLivesStr = AppFig.getFeatureValue("max_lives"),
           let maxLives = Int(maxLivesStr) {
            playerLives = maxLives
        } else {
            playerLives = 3  // Fallback
        }

        // Apply to UI
        livesLabel.text = "Lives: \(playerLives)"
    }

    @IBAction func onLevelComplete(_ sender: UIButton) {
        // TRACK: Log immediately after action
        AppFig.logEvent(name: "level_complete", parameters: [
            "level": "\(currentLevel)"
        ])

        // Re-evaluate features that depend on level
        checkNewUnlocks()
    }

    func onSubscriptionPurchased(tier: String) {
        // Update property when it changes
        AppFig.setUserProperty(key: "subscription_tier", value: tier)

        // Re-evaluate premium features
        updatePremiumFeatures()
    }
}
```

### Timing Best Practices

#### Initialize Once at Launch

```swift
// ✅ CORRECT: Initialize in app delegate
func application(_ application: UIApplication,
                 didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    AppFig.initialize(companyId: "...", tenantId: "...", env: "prod", apiKey: "...")
    return true
}

// ❌ WRONG: Don't initialize in every view controller
class MyViewController: UIViewController {
    override func viewDidLoad() {
        AppFig.initialize(...)  // Bad! SDK already initialized
    }
}
```

#### Log Events Immediately

```swift
// ✅ CORRECT: Log right when action happens
@IBAction func purchaseButtonTapped(_ sender: UIButton) {
    AppFig.logEvent(name: "purchase_initiated")
    showPurchaseDialog()
}

// ❌ WRONG: Don't batch events
var pendingEvents: [String] = []

func onLevelComplete() {
    pendingEvents.append("level_complete")  // Bad!
}
```

#### Cache Feature Values

```swift
// ✅ CORRECT: Check once and cache
class GameViewController: UIViewController {
    private var hasDoubleXP = false

    override func viewDidLoad() {
        super.viewDidLoad()
        hasDoubleXP = AppFig.isFeatureEnabled("double_xp")
    }

    func calculateXP(_ baseXP: Int) -> Int {
        return hasDoubleXP ? baseXP * 2 : baseXP
    }
}

// ❌ WRONG: Don't check repeatedly
func update() {
    if AppFig.isFeatureEnabled("double_xp") {  // Bad!
        applyDoubleXP()
    }
}
```

---

## API Reference

### Initialization

```swift
AppFig.initialize(
    companyId: String,                         // Required: Your company ID
    tenantId: String,                          // Required: Your tenant/project ID
    env: String,                               // Required: "dev" or "prod"
    apiKey: String,                            // Required: Your API key
    autoRefresh: Bool = true,                  // Optional: Enable auto-refresh (default: true) ✨ NEW DEFAULT
    pollInterval: TimeInterval = 43200000,     // Optional: leave out to follow your plan
    debugMode: Bool = false,                   // Optional: Enable debug logging (default: false) ✨ NEW
    sessionTimeoutMs: Int64 = 1800000,         // Optional: 30 minutes (default: 30 min) ✨ NEW
    maxEvents: Int = 5000,                     // Optional: Max events (default: 5000, max: 100000)
    maxEventAgeDays: Int = 7,                  // Optional: Max age in days (default: 7, max: 365)
    cdnBaseUrl: String? = nil                  // Optional: rules host (default: production) 🆕 2.3
)
```

**Parameters:**
- `companyId` (required) - Your company ID from AppFig dashboard
- `tenantId` (required) - Your tenant/project ID from AppFig dashboard
- `env` (required) - Environment: `"dev"` or `"prod"`
- `apiKey` (required) - Your API key from AppFig dashboard
- `autoRefresh` (optional) - Enable automatic background rule updates (default: **true**) ⚠️ **Breaking Change**
- `pollInterval` (optional) - Auto-refresh interval in milliseconds. Leave it out and the SDK checks for changes every minute, on every plan 🆕 **New in 2.3**. A value you set is kept, but never faster than your plan allows.
- `debugMode` (optional) - Enable debug logging to console (default: false) 🆕 **New in v2.0**
- `sessionTimeoutMs` (optional) - Session timeout in milliseconds (default: 1800000 = 30 min, range: 60000-7200000) 🆕 **New in v2.0**
- `maxEvents` (optional) - Maximum events to store in UserDefaults (100-100000, default: 5000)
- `maxEventAgeDays` (optional) - Maximum age of events in days (1-365, default: 7)
- `cdnBaseUrl` (optional) - The rules host to read from, e.g. `https://rules-stage.appfig.com` for a staging build. Leave it out for production (`https://rules-prod.appfig.com`). Must start with `https://`. 🆕 **New in 2.3**

**Examples:**

```swift
// Basic initialization (auto-refresh enabled by default)
AppFig.initialize(
    companyId: "acme-games",
    tenantId: "space-shooter",
    env: "prod",
    apiKey: "sk_live_abc123"
)

// With a fixed poll interval (1 hour)
AppFig.initialize(
    companyId: "acme-games",
    tenantId: "space-shooter",
    env: "prod",
    apiKey: "sk_live_abc123",
    autoRefresh: true,          // Explicit (but this is already the default)
    pollInterval: 3600000       // 1 hour
)

// With debug mode enabled (useful during development)
AppFig.initialize(
    companyId: "acme-games",
    tenantId: "space-shooter",
    env: "dev",                 // Use dev environment
    apiKey: "sk_test_abc123",
    autoRefresh: true,
    pollInterval: 600000,       // 10 minutes for faster testing
    debugMode: true             // See all SDK operations in console
)

// With all parameters customized
AppFig.initialize(
    companyId: "acme-games",
    tenantId: "space-shooter",
    env: "prod",
    apiKey: "sk_live_abc123",
    autoRefresh: true,
    pollInterval: 3600000,
    debugMode: false,
    sessionTimeoutMs: 900000,   // 15 minutes instead of 30
    maxEvents: 10000,           // Store more events
    maxEventAgeDays: 30         // Keep events for 30 days
)

// Disable auto-refresh (opt-out, manual refresh only)
AppFig.initialize(
    companyId: "acme-games",
    tenantId: "space-shooter",
    env: "prod",
    apiKey: "sk_live_abc123",
    autoRefresh: false          // Must call refreshRules() manually
)
```

### Logging Events

```swift
AppFig.logEvent(name: String, parameters: [String: String]? = nil)
```

**Examples:**
```swift
// Simple event
AppFig.logEvent(name: "level_complete")

// Event with parameters
AppFig.logEvent(name: "purchase_made", parameters: [
    "item_id": "sword_legendary",
    "price": "9.99",
    "currency": "USD"
])

// Screen view (auto-tracked by SDK too)
AppFig.logScreenView(screenName: "main_menu", previousScreen: "settings")
```

### Checking Features

```swift
AppFig.isFeatureEnabled(_ feature: String) -> Bool
AppFig.getFeatureValue(_ feature: String) -> String?
```

**Examples:**
```swift
// Boolean check (returns true if value == "on")
if AppFig.isFeatureEnabled("new_ui") {
    loadNewUI()
} else {
    loadOldUI()
}

// Get actual value
if let maxLives = AppFig.getFeatureValue("max_lives") {
    playerLives = Int(maxLives) ?? 3
}

// Handle nil (no matching rules)
if let bonus = AppFig.getFeatureValue("veteran_bonus") {
    applyBonus(bonus) // "2x", "1.5x", etc.
} else {
    print("No bonus active")
}
```

### Setting Properties

```swift
// User properties
AppFig.setUserProperty(key: String, value: String)
AppFig.removeUserProperty(key: String)

// Device properties
AppFig.setDeviceProperty(key: String, value: String)
AppFig.removeDeviceProperty(key: String)

// App version
AppFig.setAppVersion(_ version: String)
```

**Examples:**
```swift
// User properties
AppFig.setUserProperty(key: "subscription_tier", value: "premium")
AppFig.setUserProperty(key: "account_age_days", value: "30")
AppFig.setUserProperty(key: "player_level", value: "15")

// Device properties (most are auto-detected)
AppFig.setAppVersion("1.2.3")
AppFig.setDeviceProperty(key: "graphics_quality", value: "high")

// Remove properties
AppFig.removeUserProperty(key: "subscription_tier")
```

### Auto-Detected Device Properties

These are automatically set by the SDK on initialization:

```
platform          "iOS", "iPadOS"
os_version        "17.0", "16.5", "15.0"
language          "English", "Japanese", "Spanish"
timezone          "America/Los_Angeles", "Asia/Tokyo"
country           "US", "JP", "GB" (requires internet on first run)
device_brand      "Apple"
device_model      "iPhone 15 Pro", "iPad Air", "iPhone SE"
```

### Session Tracking

Automatically tracked:

```swift
// These events are logged automatically:
"first_open"     // First time app opens (persisted in UserDefaults)
"session_start"  // App comes to foreground
"session_end"    // App goes to background or 10 minutes of inactivity
"screen_view"    // When you call logScreenView()
```

### Manual Refresh

```swift
AppFig.refreshRules()  // Manually reload rules from CDN
```

**Example:**
```swift
// Manually refresh rules (useful for pull-to-refresh)
AppFig.refreshRules()
```

**Note:** `setAutoRefresh()` and `setPollInterval()` are deprecated. Use the `autoRefresh` and `pollInterval` parameters in `initialize()` instead.

### Feature Reset (Recurring Triggers)

```swift
AppFig.resetFeature(_ featureName: String)
AppFig.resetAllFeatures()
```

Reset a feature's cached value and force re-evaluation. Useful for implementing recurring triggers like "show popup every 3 events".

**Example:**
```swift
// Check if feature is enabled
if AppFig.isFeatureEnabled("level_complete_popup") {
    showPopup(message: "You've completed 3 levels!")

    // Reset so it triggers again after next 3 events
    AppFig.resetFeature("level_complete_popup")
}

// With event logging
func onLevelComplete(level: Int) {
    AppFig.logEvent(name: "level_complete", parameters: ["level": String(level)])

    // Check for milestone reward
    if AppFig.isFeatureEnabled("milestone_reward") {
        showReward()
        AppFig.resetFeature("milestone_reward")
    }
}
```

**Use Cases:**
- Show popup every N events (e.g., every 3 level completions)
- Recurring promotions after X purchases
- Periodic reward unlocks
- Time-based feature re-triggers

See [Feature Reset Guide](../../SDKs/FEATURE_RESET_GUIDE.md) for detailed examples.

### Debugging

```swift
AppFig.hasRulesLoaded() -> Bool
AppFig.getEventHistoryStats() -> [String: Any]
```

**Example:**
```swift
if AppFig.hasRulesLoaded() {
    print("Rules are loaded")
}

let stats = AppFig.getEventHistoryStats()
print("Event count: \(stats["count"] ?? 0)")
print("Size: \(stats["sizeMB"] ?? 0) MB")
```

## SwiftUI Integration

### App Entry Point

```swift
import SwiftUI

@main
struct MyApp: App {

    init() {
        // Initialize AppFig
        AppFig.initialize(
            companyId: "acme-games",
            tenantId: "my-app",
            env: "prod",
            apiKey: "sk_live_abc123",
            autoRefresh: true
        )
    }

    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}
```

### Feature Wrapper

```swift
struct FeatureView<Content: View>: View {
    let featureName: String
    let content: Content

    init(_ featureName: String, @ViewBuilder content: () -> Content) {
        self.featureName = featureName
        self.content = content()
    }

    var body: some View {
        if AppFig.isFeatureEnabled(featureName) {
            content
        }
    }
}

// Usage
struct ContentView: View {
    var body: some View {
        VStack {
            Text("Welcome!")

            FeatureView("premium_banner") {
                PremiumBanner()
            }
        }
    }
}
```

## Best Practices

### 1. Initialize Early

Initialize in AppDelegate or App struct:

```swift
@main
class AppDelegate: UIResponder, UIApplicationDelegate {
    func application(_ application: UIApplication,
                    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        AppFig.initialize(
            companyId: "company",
            tenantId: "tenant",
            env: "prod",
            apiKey: "api-key",
            autoRefresh: true
        )
        return true
    }
}
```

### 2. Cache Feature Values

```swift
// ❌ Bad: Checks every frame
override func draw(_ rect: CGRect) {
    if AppFig.isFeatureEnabled("double_xp") {
        // ...
    }
}

// ✅ Good: Check once, store result
private lazy var hasDoubleXP = AppFig.isFeatureEnabled("double_xp")

override func draw(_ rect: CGRect) {
    if hasDoubleXP {
        // ...
    }
}
```

### 3. Handle Nil Values

```swift
let maxLives = Int(AppFig.getFeatureValue("max_lives") ?? "5") ?? 5
```

### 4. Log Events Liberally

```swift
func completeLevel(_ level: Int, stars: Int, timeSeconds: Int) {
    AppFig.logEvent(name: "level_complete", parameters: [
        "level_number": "\(level)",
        "time_seconds": "\(timeSeconds)",
        "stars": "\(stars)"
    ])
}
```

## Troubleshooting

### "Framework not found: AppFig"

**Problem:** Xcode can't find the AppFig framework

**Solutions:**
1. Verify the AppFigSDK package (or `AppFigSDK.xcframework`) is in your project navigator
2. Check "Embed & Sign" is selected in Frameworks, Libraries, and Embedded Content
3. Clean build folder (Product → Clean Build Folder)
4. Restart Xcode

### Code signing issues

**Problem:** "Code signing failed" or "Framework not properly signed"

**Solutions:**
1. Ensure "Embed & Sign" is selected (not "Embed Without Signing")
2. Verify your provisioning profile includes framework embedding
3. Check code signing settings in Build Settings

### "AppFig not initialized"

**Problem:** Calling SDK methods before `initialize()`

**Solution:**
```swift
func application(_ application: UIApplication,
                didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    AppFig.initialize(...)  // Must be first!
    AppFig.logEvent(name: "app_open")  // Now OK
    return true
}
```

### Feature always returns nil

**Problem:** No rules match for this feature

**Solutions:**
1. Check feature name spelling (case-sensitive)
2. Verify rules are loaded: `AppFig.hasRulesLoaded()`
3. Log relevant events/properties before checking feature
4. Check console for AppFig debug messages

### Rules not updating

**Problem:** Changes in dashboard not reflected in app

**Solutions:**
1. Enable auto-refresh in `initialize()` with desired poll interval
2. Call `AppFig.refreshRules()` manually
3. Check console for AppFig messages
4. Verify internet connection

## Performance Tips

### Event History Management

The SDK automatically manages event history to maintain optimal performance. Events are automatically trimmed based on:
- Maximum event count (default: 5000)
- Maximum event age (default: 7 days)

### Memory and CPU Usage

AppFig has minimal memory and CPU overhead:
- Low memory footprint suitable for mobile devices
- Fast feature checks with intelligent caching
- Efficient rule evaluation

## Next Steps

- **[Rule Schema](https://appfig.com/docs/rule-schema)** - All rule options
- **[Testing Guide](https://appfig.com/docs/testing)** - Test your features
