# Initialize Start the SDK once, as early as your game starts, with your app key and the player's consent. *NGA SDK 0.1.0 preview: you install 0.1.0 from Maven Central and NGA's public repositories. Every 0.x version is a preview under the NGA SDK License, and the API can change until 1.0. Questions: hi@nga.network. This page: https://nga.io/docs/sdk/initialize/* ## Where to call it | Engine | Call `initialize` from | | --- | --- | | Unity | `Awake` of a bootstrap object in your first scene, kept across scenes with `DontDestroyOnLoad` | | Android | your `Application` subclass's `onCreate`, in the app's main process | | iOS | your app delegate's `application(_:didFinishLaunchingWithOptions:)` | Call it on every launch. It returns immediately; `onInitialized` is called later, on the main thread (in Unity, the game thread). A launch in the background, by a push, a job or a broadcast receiver, calls it too: the SDK starts no load of its own (prefetch, auto-reload, refills) while the game is behind, and starts them when it comes to the front. To call it after your consent platform has answered instead, see [Initializing later](#initializing-later). **Unity (C#)** `NGABootstrap.cs` ```csharp using UnityEngine; using NGA; // On a GameObject in your first scene. It starts the SDK once and lives across scenes. public class NGABootstrap : MonoBehaviour, NGAListener { const string AppKey = "app_YOURAPPKEY"; // this game's app key, from the portal static bool started; [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.SubsystemRegistration)] static void ResetForPlayMode() => started = false; // play mode without domain reload void Awake() { if (started) { Destroy(gameObject); return; } // a second copy when the scene reloads started = true; DontDestroyOnLoad(gameObject); if (Debug.isDebugBuild) NGASDK.SetLogLevel(NGALogLevel.Debug); // The player's consent as your consent screen last stored it; Unknown() if you have none. // See Consent, age and privacy. var consent = NGAConsent.Unknown(); var config = new NGAConfig.Builder(AppKey, consent) .TestMode(Debug.isDebugBuild) .Build(); NGASDK.Initialize(config, this); } public void OnInitialized(NGAInitResult result) { if (result.Success) Debug.Log($"NGA ready (from cache: {result.FromCache})"); else Debug.LogWarning($"NGA init failed: {result.Error}"); } public void OnError(NGAError error) => Debug.LogWarning($"NGA: {error}"); public void OnAdClosedAfterRestart(string placementId, string opportunityId, bool rewardGranted) { // An NGA ad was on screen when the game was killed. If it was rewarded and rewardGranted is true, // pay the reward here unless you already did (see Full-screen backfill > Rewarded). } } ``` The same script runs the SDK in your Android and iOS builds. In the Unity Editor the SDK does not run: `OnInitialized` reports `INVALID_CONFIG / platform.unsupported` once, and every other call behaves as after a failed init, without throwing. Test on an Android or iOS device. **Android (Kotlin)** `GameApp.kt` ```kotlin import android.app.Application import android.content.pm.ApplicationInfo import android.util.Log import network.nga.sdk.NGAConfig import network.nga.sdk.NGAConsent import network.nga.sdk.NGAError import network.nga.sdk.NGAInitResult import network.nga.sdk.NGAListener import network.nga.sdk.NGALogLevel import network.nga.sdk.NGASDK class GameApp : Application() { override fun onCreate() { super.onCreate() val debuggable = applicationInfo.flags and ApplicationInfo.FLAG_DEBUGGABLE != 0 if (debuggable) NGASDK.setLogLevel(NGALogLevel.DEBUG) // The player's consent as your consent screen last stored it; unknown() if you have none. // See Consent, age and privacy. val consent = NGAConsent.unknown() val config = NGAConfig.Builder(APP_KEY, consent) .testMode(debuggable) .build() NGASDK.initialize(this, config, object : NGAListener { override fun onInitialized(result: NGAInitResult) { if (result.success) Log.i("Game", "NGA ready (from cache: ${result.fromCache})") else Log.w("Game", "NGA init failed: ${result.error}") } override fun onError(error: NGAError) { Log.w("Game", "NGA: $error") } override fun onAdClosedAfterRestart(placementId: String, opportunityId: String, rewardGranted: Boolean) { // An NGA ad was on screen when the game was killed. If it was rewarded and rewardGranted is // true, pay the reward here unless you already did (see Full-screen backfill > Rewarded). } }) } companion object { const val APP_KEY = "app_YOURAPPKEY" // this game's app key, from the portal } } ``` Register the class in your manifest if it is not already: `AndroidManifest.xml` ```xml ``` The SDK runs in your app's main process only: the one your manifest names with `android:process` on ``, if it renames it, or else the one named after your package. Called from any other process, `initialize` fails with `INVALID_CONFIG / platform.unsupported` once and does nothing else. **iOS (Swift)** `AppDelegate.swift` ```swift import UIKit import NGASDK // Your existing app delegate: keep its @main (or @UIApplicationMain) as it is. final class AppDelegate: UIResponder, UIApplicationDelegate, NGAListener { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { #if DEBUG let debugBuild = true #else let debugBuild = false #endif if debugBuild { NGASDK.setLogLevel(.debug) } // The player's consent as your consent screen last stored it; unknown() if you have none. // See Consent, age and privacy. let consent = NGAConsent.unknown() let config = NGAConfig.Builder(appKey: "app_YOURAPPKEY", consent: consent) // the app key, from the portal .testMode(debugBuild) .build() NGASDK.initialize(config: config, listener: self) return true } func onInitialized(_ result: NGAInitResult) { if result.success { print("NGA ready (from cache: \(result.fromCache))") } else { print("NGA init failed: \(result.error?.description ?? "unknown")") } } func onError(_ error: NGAError) { print("NGA: \(error)") } func onAdClosedAfterRestart(placementId: String, opportunityId: String, rewardGranted: Bool) { // An NGA ad was on screen when the game was killed. If it was rewarded and rewardGranted is true, // pay the reward here unless you already did (see Full-screen backfill > Rewarded). } } ``` A SwiftUI app attaches this delegate with `@UIApplicationDelegateAdaptor(AppDelegate.self)`. In Swift 6 language mode, declare the conformance `@preconcurrency NGAListener`; see [Threads](https://nga.io/docs/sdk/reference/#threads). The SDK does not run in an app extension: there, `initialize` fails with `INVALID_CONFIG / platform.unsupported`. ## The app key One app key per game, shared by its Android and iOS builds. Format: `app_` followed by 8 to 64 letters or digits. Copy it from the game's *Overview* > *App key and integration* in the portal ([The app key](https://nga.io/docs/sdk/portal/#the-app-key)). | Cause | `initialize` fails with | | --- | --- | | The key is not in the `app_` format | `INVALID_CONFIG / app_key.format`, immediately | | The server does not know the key, the example `app_YOURAPPKEY` included | `INVALID_CONFIG / app_key.unknown` | | A release build's package name (Android) or bundle id (iOS) is not the one registered for the game | `INVALID_CONFIG / app_key.unknown` | | The game is registered for the other platform only, for example an iOS build of a game added with its Play link alone | `INVALID_CONFIG / app_key.unknown`; add the platform on the game's *Overview* (*Add iOS*, *Add Android*) | The last three look alike from the SDK. The game's *Overview* in the portal shows its platforms, and *Store and builds* the package name or bundle id registered and the ones your builds reported. ## Consent at start Consent is required. Pass the player's last stored answer, not a constant, or `NGAConsent.unknown()` if you have no answer yet or your consent platform writes the IAB TCF keys. How the builder's value and `setConsent` combine: [Consent](https://nga.io/docs/sdk/privacy/#consent). ## Test mode `testMode(true)` marks everything this install sends as test traffic. The snippets above turn it on for debug builds only. What test mode does, and how a registered device turns it on for release builds too: [Test mode](https://nga.io/docs/sdk/testing/#test-mode). ## The answer Every `initialize` call gets exactly one `onInitialized`, with an `NGAInitResult`: | `success` | `fromCache` | Means | | --- | --- | --- | | true | false | NGA answered with your configuration. | | true | true | The SDK started from the configuration it saved last time, online or not; it fetches a fresh one in the background. This is how a game starts offline. | | false | — | `error` says why. | A failure is one of two kinds: - **Retryable** (`error.retryable` is true): no network, a timeout, or a server error, with no saved configuration to start from. You do nothing: the SDK keeps retrying in the background, and when a retry succeeds the SDK is ready with no further `onInitialized`. - **Not retryable**: the app key is malformed, unknown or switched off (`INVALID_CONFIG`, `DISABLED`). Fix the key; the SDK does not retry. Every error code, with its cause and fix, is on [Errors](https://nga.io/docs/sdk/reference/errors/). `onError` reports problems after init: the app key switched off, this SDK version or build retired, calls made before a failed init thrown away. `onAdClosedAfterRestart` reports an ad that was on screen when the game was killed; see [Rewarded](https://nga.io/docs/sdk/backfill/#rewarded). The latest 5 reports that come while no listener is set are kept, and delivered after the `onInitialized` of the `initialize` call that sets one. ## Calls before `initialize` You can call anything at any time: - Setters (`setLogLevel`, `setConsent`, `setAge`, `setCustomerUserId`, `setMuted` and the impression listener) apply immediately, even before `initialize`. Consent, age and the user id are saved immediately. On Android, while the device's storage is unavailable (a phone still locked after a restart, a full disk), they still apply at once and are saved as soon as storage is available. - Other calls are queued in order until init succeeds, up to 200. The 201st call is dropped; a dropped call with a callback gets `NOT_INITIALIZED / queue.full`. - If init fails permanently, queued calls with a callback get `NOT_INITIALIZED / init.failed`. The first call made before any `initialize` logs one warning naming `initialize`, so a missing call shows in the log. ## Initializing later You can call `initialize` later than the launch, for example once your consent platform has answered (Google's UMP needs an Activity, so its answer comes after `Application.onCreate`). The SDK sees that the app is already in the foreground and starts the session then. Until the call: - the setters apply and are saved, as above, so `setConsent` with the platform's answer can come first; - every other call waits, up to 200; - nothing is recorded: sessions, purchases and your mediation's revenue are captured from `initialize` on, so a purchase or a MAX or LevelPlay impression before it is lost. Still call it once per launch, on every launch, and before your mediation if you use [full-screen backfill](https://nga.io/docs/sdk/backfill/#the-order-at-startup). ## Calling `initialize` again Each call gets its own `onInitialized`: the current result, or the result of the next attempt. - Same app key: a non-null listener replaces the earlier one for `onError` and `onAdClosedAfterRestart`. Its consent applies like any builder's. - Different app key: fails with `INVALID_CONFIG / app_key.changed` and changes nothing. ## Log level `setLogLevel` sets how much the SDK writes to the device log: `NONE`, `ERROR`, `WARN` (the default), `INFO` or `DEBUG`. Set `DEBUG` before `initialize` to see init itself, including your device's test-device id. Outside test mode the log never prints a player's identifiers. Where to find the log: [The log](https://nga.io/docs/sdk/testing/#the-log). ## Threads Call from any thread; no call blocks. Callbacks always arrive on the main thread, after the call has returned. More: [Threads](https://nga.io/docs/sdk/reference/#threads). ## Next Set up [consent, age and privacy](https://nga.io/docs/sdk/privacy/), then add the [native banner](https://nga.io/docs/sdk/native-cross-promo/) or [full-screen backfill](https://nga.io/docs/sdk/backfill/).