> ## Documentation Index
> Fetch the complete documentation index at: https://docs.permutive.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Initialization

> Configure and start the Permutive SDK

The SDK must be initialized before tracking events or accessing cohort data. Initialization is asynchronous and should happen early in your app lifecycle.

## Basic Initialization

```swift Swift theme={"dark"}
import Permutive_iOS

func initializePermutive() {
    guard let options = Options(
        apiKey: "<your-api-key>",
        organisationId: "<your-organisation-id>",
        workspaceId: "<your-workspace-id>"
    ) else {
        print("Failed to create Permutive options")
        return
    }

    Permutive.shared.start(with: options) { error in
        if let error = error {
            print("Permutive initialization failed: \(error.localizedDescription)")
            return
        }
        print("Permutive SDK ready")
    }
}
```

```objectivec Objective-C theme={"dark"}
@import Permutive_iOS;

- (void)initializePermutive {
    PermutiveOptions *options = [[PermutiveOptions alloc]
        initWithApiKey:@"<your-api-key>"
        organisationId:@"<your-organisation-id>"
        workspaceId:@"<your-workspace-id>"];

    if (options == nil) {
        NSLog(@"Failed to create Permutive options");
        return;
    }

    [[Permutive shared] startWith:options
                          context:nil
                       completion:^(NSError *error) {
        if (error != nil) {
            NSLog(@"Permutive initialization failed: %@", error.localizedDescription);
            return;
        }
        NSLog(@"Permutive SDK ready");
    }];
}
```

## Configuration Options

The `Options` class accepts several configuration parameters:

### Required Parameters

| Parameter | Type | Description |
| - | - | - |
| `apiKey` | `String` | Your Permutive API key |
| `organisationId` | `String` | Your Permutive organisation ID |
| `workspaceId` | `String` | Your Permutive workspace ID |

### Optional Configuration

```swift Swift theme={"dark"}
guard let options = Options(
    apiKey: "<your-api-key>",
    organisationId: "<your-organisation-id>",
    workspaceId: "<your-workspace-id>"
) else { return }

// Enable debug logging
options.logModes = LogMode.all

// Start with options
Permutive.shared.start(with: options) { error in
    // Handle completion
}
```

```objectivec Objective-C theme={"dark"}
PermutiveOptions *options = [[PermutiveOptions alloc]
    initWithApiKey:@"<your-api-key>"
    organisationId:@"<your-organisation-id>"
    workspaceId:@"<your-workspace-id>"];

// Enable debug logging
options.logModes = PermutiveLogModeAll;

[[Permutive shared] startWith:options context:nil completion:^(NSError *error) {
    // Handle completion
}];
```

### Log Modes

Control what the SDK logs to the console:

| Mode | Description |
| - | - |
| `LogMode.none` | No logging (default for production) |
| `LogMode.all` | All messages (recommended for development) |
| `LogMode.info` | Informational messages only |
| `LogMode.error` | Error messages only |

## Where to Initialize

### UIKit - AppDelegate

```swift Swift theme={"dark"}
import UIKit
import Permutive_iOS

@main
class AppDelegate: UIResponder, UIApplicationDelegate {

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

    private func initializePermutive() {
        guard let options = Options(
            apiKey: "<your-api-key>",
            organisationId: "<your-organisation-id>",
            workspaceId: "<your-workspace-id>"
        ) else { return }

        Permutive.shared.start(with: options) { error in
            if let error = error {
                print("Permutive error: \(error)")
            }
        }
    }
}
```

```objectivec Objective-C theme={"dark"}
#import "AppDelegate.h"
@import Permutive_iOS;

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application
    didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [self initializePermutive];
    return YES;
}

- (void)initializePermutive {
    PermutiveOptions *options = [[PermutiveOptions alloc]
        initWithApiKey:@"<your-api-key>"
        organisationId:@"<your-organisation-id>"
        workspaceId:@"<your-workspace-id>"];

    [[Permutive shared] startWith:options context:nil completion:^(NSError *error) {
        if (error != nil) {
            NSLog(@"Permutive error: %@", error);
        }
    }];
}

@end
```

### SwiftUI - App Struct

```swift theme={"dark"}
import SwiftUI
import Permutive_iOS

@main
struct MyApp: App {
    init() {
        initializePermutive()
    }

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

    private func initializePermutive() {
        guard let options = Options(
            apiKey: "<your-api-key>",
            organisationId: "<your-organisation-id>",
            workspaceId: "<your-workspace-id>"
        ) else { return }

        Permutive.shared.start(with: options) { error in
            if let error = error {
                print("Permutive error: \(error)")
            }
        }
    }
}
```

## Consent Considerations

> [!WARNING]
>
> The Permutive SDK assumes consent has been obtained before initialization. If your app requires user consent for tracking, complete your consent flow before calling `start(with:)`.

The SDK does not call Apple's App Tracking Transparency (ATT) framework. If you need ATT consent:

```swift theme={"dark"}
import AppTrackingTransparency

func requestConsentThenInitialize() {
    if #available(iOS 14, *) {
        ATTrackingManager.requestTrackingAuthorization { status in
            switch status {
            case .authorized:
                self.initializePermutive()
            case .denied, .restricted:
                // Handle accordingly - you may still initialize
                // Permutive without IDFA tracking
                self.initializePermutive()
            case .notDetermined:
                break
            @unknown default:
                break
            }
        }
    } else {
        initializePermutive()
    }
}
```

> [!NOTE]
>
> **IDFA is not required.** Permutive works effectively without IDFA. Consider using `identifierForVendor` or hashed email addresses instead. See [IDFA Provider](https://docs.permutive.com/sdks/mobile/ios/integrations/idfa-provider.md) for details.

## Initialization with Context

You can provide initial context during initialization:

```swift Swift theme={"dark"}
let context = Context(
    title: "App Launch",
    url: URL(string: "https://example.com/app"),
    referrer: nil
)

Permutive.shared.start(with: options, context: context) { error in
    // Handle completion
}
```

```objectivec Objective-C theme={"dark"}
PermutiveContext *context = [[PermutiveContext alloc]
    initWithTitle:@"App Launch"
    url:[NSURL URLWithString:@"https://example.com/app"]
    referrer:nil];

[[Permutive shared] startWith:options context:context completion:^(NSError *error) {
    // Handle completion
}];
```

## Checking Initialization Status

The SDK provides properties to check its current state:

```swift theme={"dark"}
// Get the current user ID (available after initialization)
let userId = Permutive.shared.currentUserId

// Check current cohorts
let cohorts = Permutive.shared.cohorts
```

## Error Handling

Handle initialization errors appropriately:

```swift Swift theme={"dark"}
Permutive.shared.start(with: options) { error in
    if let error = error {
        // Log the error for debugging
        print("Permutive initialization failed: \(error.localizedDescription)")

        // Optionally report to your error tracking service
        // ErrorTracker.report(error)

        // The app can continue without Permutive
        // SDK calls will be no-ops or return empty data
        return
    }

    // SDK is ready - proceed with tracking
    print("Permutive ready, user ID: \(Permutive.shared.currentUserId)")
}
```

```objectivec Objective-C theme={"dark"}
[[Permutive shared] startWith:options context:nil completion:^(NSError *error) {
    if (error != nil) {
        NSLog(@"Permutive initialization failed: %@", error.localizedDescription);
        return;
    }

    NSLog(@"Permutive ready, user ID: %@", [[Permutive shared] currentUserId]);
}];
```

## tvOS Considerations

> [!NOTE]
>
> **tvOS Note:** The initialization process is identical on tvOS. The SDK automatically handles platform differences. App Tracking Transparency and IDFA are available on tvOS from version 14.5 onwards.

## Best Practices

> [tab] Do
>
> * Initialize as early as possible in the app lifecycle
> * Handle initialization errors gracefully
> * Complete consent flows before initialization
> * Enable debug logging during development
> * Store credentials securely (consider using a configuration file or build settings)

> [tab] Don't
>
> * Don't initialize multiple times
> * Don't block the main thread waiting for initialization
> * Don't hard-code credentials in source control
> * Don't assume immediate availability of cohort data after initialization

## Troubleshooting

> [accordion] Initialization fails silently
>
> **Problem:** No error, but SDK doesn't seem to work.
>
> **Solutions:**
>
> * Enable debug logging: `options.logModes = LogMode.all`
> * Check credentials are correct
> * Verify network connectivity

> [accordion] Invalid credentials error
>
> **Problem:** Initialization fails with credential error.
>
> **Solutions:**
>
> * Verify API key, organization ID, and workspace ID from your dashboard
> * Check for extra whitespace or newlines in credential strings
> * Ensure credentials match the correct environment (staging vs production)

> [accordion] SDK not ready when tracking
>
> **Problem:** Events tracked before initialization completes are lost.
>
> **Solution:** Wait for the completion callback before tracking:
>
> ```swift theme={"dark"}
> Permutive.shared.start(with: options) { error in
>     guard error == nil else { return }
>     // Now safe to track
>     self.startTracking()
> }
> ```

## Next Steps

> [card] [Verification](https://docs.permutive.com/sdks/mobile/ios/getting-started/verification.md)
>
> Verify your integration is working

> [card] [Page Tracking](https://docs.permutive.com/sdks/mobile/ios/features/page-tracking.md)
>
> Track page views and engagement


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.