---
title: "SDK Initialization"
canonical_url: "https://apidocs.sportradar.com/resources/virtual-stadium/docs/ios/initialization"
markdown_url: "https://apidocs.sportradar.com/resources/virtual-stadium/docs/ios/initialization.md"
last_updated: "2026-06-04T06:36:21Z"
---

# SDK Initialization

Before using any Virtual Stadium UI components, you must initialize the SDK in your iOS application. This guide covers the initialization process and essential configuration steps.

***

## Initialize the SDK

The SDK must be initialized once when your application starts. You can choose between two approaches: using an `AppDelegate` (traditional approach) or using SwiftUI's lifecycle methods (modern approach).

### Option 1: Using AppDelegate (Recommended)

Create an `AppDelegate` and initialize the SDK:
***AppDelegate.swift:***

```swift
import UIKit
import VirtualStadiumSDK

class AppDelegate: NSObject, UIApplicationDelegate {
    func application(
        _ application: UIApplication,
        didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil
    ) -> Bool {
        // Initialize Virtual Stadium SDK
        Task {
            do {
                try await Managers.SDK.shared.initialize()
                print("SDK initialized successfully")
            } catch {
                print("Failed to initialize SDK: \(error)")
            }
        }
        return true
    }
}
```

Then register your `AppDelegate` in your main `App` struct:
***YourApp.swift:***

```swift
import SwiftUI

@main
struct YourApp: App {
    @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
    
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}
```

### Option 2: Using SwiftUI Lifecycle

Alternatively, initialize the SDK directly in your `App` struct using the `init()` method:
***YourApp.swift:***

```swift
import SwiftUI
import VirtualStadiumSDK

@main
struct YourApp: App {
    
    init() {
        // Initialize Virtual Stadium SDK
        Task {
            do {
                try await Managers.SDK.shared.initialize()
                print("SDK initialized successfully")
            } catch {
                print("Failed to initialize SDK: \(error)")
            }
        }
    }
    
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}
```

Or use the `.task` modifier on your root view:
***YourApp.swift:***

```swift
import SwiftUI
import VirtualStadiumSDK

@main
struct YourApp: App {
    @State private var isSDKInitialized = false
    
    var body: some Scene {
        WindowGroup {
            if isSDKInitialized {
                ContentView()
            } else {
                ProgressView("Initializing...")
                    .task {
                        do {
                            try await Managers.SDK.shared.initialize()
                            isSDKInitialized = true
                            print("SDK initialized successfully")
                        } catch {
                            print("Failed to initialize SDK: \(error)")
                        }
                    }
            }
        }
    }
}
```

> **Tip**
>
> The `initialize()` method should be called only once, when your application launches. Calling it multiple times may cause unexpected behavior. The AppDelegate approach (Option 1) is recommended as it follows iOS conventions and ensures initialization happens at the appropriate time in the app lifecycle.

***

## Basic Chat Implementation

Once the SDK is initialized, you can implement the `ChatView` component in your SwiftUI views.

### Minimal Setup

Here's a minimal example of implementing the ChatView:
***ContentView\.swift:***

```swift
import SwiftUI
import VirtualStadiumSDK

struct ContentView: View {
    let userJWT: String = "<your-jwt-token>"
    let channelId: String = "<your-channel-id>"
    
    var body: some View {
        ChatView(
            userJWT: userJWT,
            channelId: channelId,
            supportedLanguage: .english
        )
    }
}
```

### Full Implementation With Handlers

Here's a complete example with all handlers configured:
***ChatViewContainer.swift:***

```swift
import SwiftUI
import VirtualStadiumSDK

struct ChatViewContainer: View {
    let jwt: String
    let channelId: String
    let chatSettings: ChatSettings
    
    @StateObject private var viewModel = ChatViewModel()
    @State private var showError = false
    @State private var errorMessage = ""
    
    var body: some View {
        NavigationView {
            ChatView(
                userJWT: jwt,
                channelId: channelId,
                matchStatusManager: viewModel.matchStatusManager,
                flashBetManager: viewModel.flashBetManager,
                insightsManager: viewModel.insightsManager,
                supportedLanguage: .english,
                onBetShareHandler: { completion in
                    // Handle bet sharing
                    viewModel.shareBet { betPayloads in
                        completion(betPayloads)
                    }
                },
                onCopyToBetslip: { betPayload in
                    // Handle copying bet to betslip
                    viewModel.copyToBetslip(betPayload)
                },
                onTagSelected: { tag in
                    // Handle tag selection
                    viewModel.handleTagSelection(tag)
                },
                onReachSupportTeam: { reason in
                    // Handle support team contact
                    viewModel.contactSupport(reason: reason)
                },
                onOpenProfile: { userId in
                    // Handle profile navigation
                    viewModel.openProfile(userId: userId)
                },
                analyticsProvider: viewModel.analyticsProvider,
                onError: { error in
                    errorMessage = error.localizedDescription
                    showError = true
                },
                chatSettings: chatSettings
            )
            .navigationTitle("Chat")
        }
        .alert("Error", isPresented: $showError) {
            Button("OK", role: .cancel) { }
        } message: {
            Text(errorMessage)
        }
    }
}

// Example ViewModel
class ChatViewModel: ObservableObject {
    var matchStatusManager: MatchStatusManager?
    var flashBetManager: FlashBetManager?
    var insightsManager: InsightsManager?
    var analyticsProvider: AnalyticsProvider?
    
    init() {
        // Initialize your managers here
    }
    
    func shareBet(completion: @escaping ([BetPayload]) -> Void) {
        // Implement bet sharing logic
    }
    
    func copyToBetslip(_ betPayload: BetPayload) {
        // Implement bet copying logic
    }
    
    func handleTagSelection(_ tag: Tag) {
        // Implement tag selection logic
    }
    
    func contactSupport(reason: InfractionReason) {
        // Implement support contact logic
    }
    
    func openProfile(userId: String) {
        // Implement profile navigation logic
    }
}
```

1. **Step 1**

   #### Imports

   Import `SwiftUI` and `VirtualStadiumSDK`.

2. **Step 2**

   #### View Properties

   Declare the required `jwt`, `channelId`, and `chatSettings` inputs. Initialize `ChatViewModel` as a `@StateObject` and add `showError` and `errorMessage` state for error handling.

3. **Step 3**

   #### ChatView — Required Parameters

   Pass `userJWT`, `channelId`, and `supportedLanguage` to `ChatView`. Attach the optional managers from the view model for match status, flash bet, and insights features.

4. **Step 4**

   #### onBetShareHandler

   Called when the user wants to share a bet. Delegate to `viewModel.shareBet` and forward the returned bet payloads via the `completion` handler.

5. **Step 5**

   #### onCopyToBetslip & onTagSelected

   `onCopyToBetslip` is called when a user copies a bet from the chat — delegate to `viewModel.copyToBetslip`. `onTagSelected` is called when a user taps a tag — delegate to `viewModel.handleTagSelection`.

6. **Step 6**

   #### onReachSupportTeam & onOpenProfile

   `onReachSupportTeam` fires when the Contact Support button is tapped — delegate to `viewModel.contactSupport`. `onOpenProfile` fires when a user taps another user's profile — delegate to `viewModel.openProfile`.

7. **Step 7**

   #### analyticsProvider & onError

   Pass `viewModel.analyticsProvider` for event tracking. The `onError` closure captures SDK errors into local state, which triggers the `.alert` modifier to display them to the user.

8. **Step 8**

   #### Chat settings

   Pass `chatSettings` for chat theming and general settings. This enables modification of the chat components' icons, translations, theming and other general settings.

9. **Step 9**

   #### ChatViewModel

   Holds all optional managers and exposes handler methods that the view delegates to. Implement each method with your actual business logic — bet slip fetching, betslip copying, tag navigation, support contact, and profile routing.

***

## Configuration Overview

Here's a complete checklist of the initialization and configuration steps:

| Step  | Action                          | Location                                             | Required                    |
| ----- | ------------------------------- | ---------------------------------------------------- | --------------------------- |
| **1** | Initialize SDK                  | `AppDelegate` or `App.init()`                        | ✅ Yes                       |
| **2** | Register AppDelegate (if using) | Main App struct with `@UIApplicationDelegateAdaptor` | ⚠️ Only if using Option 1   |
| **3** | Implement ChatView              | SwiftUI View                                         | ✅ Yes                       |
| **4** | Configure handlers              | ChatView parameters                                  | ⚠️ Optional but recommended |

***

## Troubleshooting

### SDK Not Initialized Error

If you see an error about the SDK not being initialized:

- Verify `Managers.SDK.shared.initialize()` is called before presenting ChatView
- Ensure your `AppDelegate` is registered using `@UIApplicationDelegateAdaptor` (if using Option 1)
- Check that the initialization completes before presenting the ChatView
- Review console logs for initialization error messages
- If using pure SwiftUI approach, ensure the loading state properly waits for initialization

### Handler Not Being Called

If your handlers (onBetShareHandler, onCopyToBetslip, etc.) aren't being called:

- Verify the handlers are not `nil`
- Check that you're providing the closure/function implementation
- Ensure the SDK is properly initialized before user interaction
- Review console logs for any error messages

### Initialization Timing Issues

If you experience timing-related issues with initialization:

- Use the AppDelegate approach (Option 1) for more reliable initialization timing
- Ensure async initialization completes before the UI that depends on it is shown
- Consider using a loading state to wait for initialization (as shown in Example 2)

***

## Next Steps

Now that the SDK is initialized and configured, you're ready to explore the chat component in detail:

**Implement Chat Component**

Learn how to add the Chat component to your app with all its parameters, features, and customization options.

[Continue to Chat →](https://apidocs.sportradar.com/resources/virtual-stadium/docs/ios/chat.md)
