> ## 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

<CodeGroup>
  ```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");
      }];
  }
  ```
</CodeGroup>

## 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

<CodeGroup>
  ```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
  }];
  ```
</CodeGroup>

### 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

<CodeGroup>
  ```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
  ```
</CodeGroup>

### 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:)`.
</Warning>

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()
    }
}
```

<Info>
  **IDFA is not required.** Permutive works effectively without IDFA. Consider using `identifierForVendor` or hashed email addresses instead. See [IDFA Provider](/sdks/mobile/ios/integrations/idfa-provider) for details.
</Info>

## Initialization with Context

You can provide initial context during initialization:

<CodeGroup>
  ```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
  }];
  ```
</CodeGroup>

## 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:

<CodeGroup>
  ```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]);
  }];
  ```
</CodeGroup>

## tvOS Considerations

<Info>
  **tvOS Note:** The initialization process is identical on tvOS. The SDK automatically handles platform differences. IDFA and App Tracking Transparency are not available on tvOS.
</Info>

## Best Practices

<Tabs>
  <Tab title="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>

  <Tab title="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
  </Tab>
</Tabs>

## Troubleshooting

<AccordionGroup>
  <Accordion title="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>

  <Accordion title="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>

  <Accordion title="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()
    }
    ```
  </Accordion>
</AccordionGroup>

## Next Steps

<CardGroup cols={2}>
  <Card title="Verification" icon="circle-check" href="/sdks/mobile/ios/getting-started/verification">
    Verify your integration is working
  </Card>

  <Card title="Page Tracking" icon="file" href="/sdks/mobile/ios/features/page-tracking">
    Track page views and engagement
  </Card>
</CardGroup>
