# NGA SDK 0.1.0 preview: the whole guide and reference 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. Every page of https://nga.io/docs/sdk/ in sidebar order, each starting at its own top-level heading. # NGA SDK 0.1.0 Promote your own games inside your games, for free, and show NGA's full-screen ad when your mediation has nothing to show. One SDK for Unity, Android and iOS. *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/* ## What 0.1.0 does - **Cross-promotion of your own games.** Every game of yours with *Shows cross-promo* on shows your other games whose *Promoted* switch is on, for free. - **Install and retention reporting.** NGA reports the impressions, clicks and installs each promotion brings, and the day-1 and day-7 retention of those installs. If you use AppsFlyer or Adjust, NGA can report to them too. - **The game's own signals.** Sessions are recorded with no extra code, and so are Google Play Billing and StoreKit 1 purchases and the ad revenue of AppLovin MAX and Unity LevelPlay. StoreKit 2 and Unity IAP 5 purchases need one call each, and Google AdMob one call per paid event. See [Revenue and purchases](https://nga.io/docs/sdk/revenue/). ## Two cross-promo formats **Native banner.** On a screen with nothing else at the bottom (for example, game over), the SDK slides up a banner with the promoted game's icon, name and one line of text. The banner uses your game's colors, and a tap opens the store. Call `close()` before you show anything else at the bottom; your own banner ad steps aside by itself once you register the banner yield. You do not place, size or track the banner yourself. See [Native cross-promo](https://nga.io/docs/sdk/native-cross-promo/). **Full-screen backfill.** When your mediation (AppLovin MAX, Unity LevelPlay or Google AdMob) fails to load an interstitial or rewarded ad, load NGA's. When it is time to show the ad, show NGA's only if the mediation still has nothing. Your code decides, and the SDK never loads ahead of a mediation failure, so NGA never takes an ad your mediation could fill. See [Full-screen backfill](https://nga.io/docs/sdk/backfill/). NGA's server decides which of your games fills each placement. Your code only loads a placement and shows what comes back. ## Two libraries The SDK is two libraries, released together at one version. | Library | Add it when | What it adds | | --- | --- | --- | | `nga-sdk`, the core library | always | `NGASDK.initialize`, consent and age, sessions, purchases, ad revenue from your mediation, and the types of the ad surface | | `nga-sdk-render`, the render library | your game shows NGA ads | the ads themselves: the native banner, interstitial and rewarded | Without the render library, ad calls return `RENDER_NOT_AVAILABLE`; everything else works. You can add it later, at the same version, without changing `initialize`. Your code always talks to one class, `NGASDK`. Package names for each engine: [Install](https://nga.io/docs/sdk/install/#what-you-add). ## Every game needs the SDK Add the SDK to every game you promote, not only to the game that shows the ad. A game that shows no NGA ads needs only the core library. A tap opens the store directly, and NGA counts the install when the promoted game first starts. To send these installs to your MMP too, give NGA its click and impression URLs. See [Attribution](https://nga.io/docs/sdk/attribution/). ## Requirements | | Minimum | | --- | --- | | Android | API 23 (Android 6.0) | | Kotlin (Kotlin apps only) | compiler 1.8 or later; the libraries bring `kotlin-stdlib` 1.9 or later. Java apps are unaffected | | iOS | iOS 15.0; Xcode 26 or later | | Unity | Unity 2022.3 LTS or later, building for Android, iOS or both | Your mediation SDK may need more: - AppLovin MAX 13 and Google Mobile Ads 25: Android API 24. - Google Mobile Ads 25.5: a Kotlin 2.2 or later compiler in a Kotlin app. - Google Mobile Ads for iOS 13.4 and later: Xcode 26.2. ## Not in 0.1.0 - Standard banner ads (320 × 50 and the like), app-open ads, playable ads, and ads for anything other than your own games. - Mediation adapters: NGA is not a network inside MAX, LevelPlay or AdMob. Backfill is your own code; see [The rule](https://nga.io/docs/sdk/backfill/#the-rule). - Promoting a game that does not carry the SDK. - Server-side reward verification. The reward is decided on the device; see [Rewarded](https://nga.io/docs/sdk/backfill/#rewarded). - A "more games" hub, and rewards for installing the promoted game. - Engines other than Unity: no Cocos, Godot, Flutter or Unreal wrapper. - iOS apps in the App Store's Kids Category. - Banner text in languages other than English; see [Players who should not see it](https://nga.io/docs/sdk/native-cross-promo/#players-who-should-not-see-it). - An API to log your own custom events. ## The preview 0.1.0 is the release, not a release candidate. Under the [NGA SDK License](https://nga.io/legal/sdk-license/) it is a preview version, as every 0.x version is. For now: - **These pages install 0.1.0.** See [Install](https://nga.io/docs/sdk/install/). - **NGA approves your studio's sign-up** in the portal by hand. Everything else in the portal is yours to do. See [Set up in the portal](https://nga.io/docs/sdk/portal/). - **The API can change** until 1.0. The [changelog](https://nga.io/docs/sdk/changelog/) carries the migration notes and the support terms. Questions at any step: [hi@nga.network](mailto:hi@nga.network). ## Start here The portal first, then the code. A new studio starts at [portal.nga.io/sign-up](https://portal.nga.io/sign-up). Choose your engine on any page; the choice holds everywhere. These sections are the path; the rest of each page is there when you need it. 1. **Portal:** [Sign up](https://nga.io/docs/sdk/portal/#sign-up), [Register a game](https://nga.io/docs/sdk/portal/#register-a-game), [Placements](https://nga.io/docs/sdk/portal/#placements). Copy the app key and placement ids. 2. **Code:** [Install](https://nga.io/docs/sdk/install/); on Initialize, [Where to call it](https://nga.io/docs/sdk/initialize/#where-to-call-it), [The app key](https://nga.io/docs/sdk/initialize/#the-app-key) and [The answer](https://nga.io/docs/sdk/initialize/#the-answer); then [Consent](https://nga.io/docs/sdk/privacy/#consent), and [Age and audience](https://nga.io/docs/sdk/privacy/#age-and-audience) for a *Mixed* game. Or [hand it to a coding agent](https://nga.io/docs/sdk/agents/). 3. **The format:** - Native banner: [Where the banner may show](https://nga.io/docs/sdk/native-cross-promo/#where-the-banner-may-show), [What the banner shows](https://nga.io/docs/sdk/native-cross-promo/#what-the-banner-shows), [Load and show](https://nga.io/docs/sdk/native-cross-promo/#load-and-show). - Full-screen backfill: [The rule](https://nga.io/docs/sdk/backfill/#the-rule), [The order at startup](https://nga.io/docs/sdk/backfill/#the-order-at-startup), [Pause and resume](https://nga.io/docs/sdk/backfill/#pause-and-resume), [Your mediation](https://nga.io/docs/sdk/backfill/#your-mediation), then [Interstitial](https://nga.io/docs/sdk/backfill/#interstitial) or [Rewarded](https://nga.io/docs/sdk/backfill/#rewarded). 4. **Test and release:** [Test mode](https://nga.io/docs/sdk/testing/#test-mode), [Register a test device](https://nga.io/docs/sdk/testing/#register-a-test-device), [The log](https://nga.io/docs/sdk/testing/#the-log), [Checklist](https://nga.io/docs/sdk/testing/#checklist); then the [release checklist](https://nga.io/docs/sdk/go-live/#release-checklist) and the [store privacy forms](https://nga.io/docs/sdk/privacy/#store-privacy-forms). Unity adds [Unity build checks](https://nga.io/docs/sdk/install/#unity-build-checks) when a build fails; iOS adds [App Tracking Transparency](https://nga.io/docs/sdk/privacy/#app-tracking-transparency); Android adds nothing. Read when you need them: [Calls before initialize](https://nga.io/docs/sdk/initialize/#calls-before-initialize), [Calling initialize again](https://nga.io/docs/sdk/initialize/#calling-initialize-again), [Log level](https://nga.io/docs/sdk/initialize/#log-level), [Threads](https://nga.io/docs/sdk/initialize/#threads), [Show lifecycle](https://nga.io/docs/sdk/native-cross-promo/#show-lifecycle), [One ad per placement](https://nga.io/docs/sdk/backfill/#one-ad-per-placement), [Attribution](https://nga.io/docs/sdk/attribution/), [Revenue and purchases](https://nga.io/docs/sdk/revenue/), [Troubleshooting](https://nga.io/docs/sdk/troubleshooting/). # Set up in the portal Sign up, register your games, and get the app key and placement ids your code uses. All of it happens in the portal, at portal.nga.io. *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/portal/* ## What you get from the portal Your code needs three things from the portal, and nothing else from NGA: | You need | Where it is | What it looks like | | --- | --- | --- | | The app key of each game | the game's *Overview*, under *App key and integration* | `app_` and letters and digits | | A placement id for each place your game shows an NGA ad | the game's *Placements* | `plc_` and an id you choose, such as `plc_example_native` | | Your test devices, registered | *Test devices* | the id the SDK prints at init | The key and the ids in these docs are examples. Use your own from the portal. The portal calls a game a *title*; these pages say "game", except in the portal's own labels. The portal's front page shows the setup below as a checklist, *Going live*, and *Getting started* walks through it in seven steps. Each game has five pages: *Overview*, *Store and builds*, *Promotion*, *Placements* and *Creatives*. ## Sign up 1. Open [portal.nga.io/sign-up](https://portal.nga.io/sign-up) and enter your work email address. NGA emails you a code to prove the address. (The portal's front page opens on sign-in, which is for studios NGA has already approved.) 2. Fill in the form: *Studio name*, *Company country*, *A store link to one of your games* and *Your role*. Under *Agreements*, accept NGA's [Studio Terms](https://nga.io/legal/studio-terms/), [Data Processing Agreement (DPA)](https://nga.io/legal/dpa/) and [SDK License](https://nga.io/legal/sdk-license/) for your studio (NGA's [Privacy Notice](https://nga.io/legal/privacy/) is linked beside them), then *Send the request*. 3. The portal shows *Request pending* until NGA approves your studio. > **During the preview.** > NGA approves each studio's sign-up by hand. You get a "You're in" email with a sign-in link once it does; until then nothing else in the portal opens. Questions about your request: [hi@nga.network](mailto:hi@nga.network). **Signing in.** Enter your address on the sign-in page. NGA emails a link and a 6-digit code; either one signs you in, for 30 days. **Teammates.** Invite them by email on *Team*. Each joins your studio as a member and sees the whole studio. An email address can belong to one studio only. ## Register a game *Titles > Add a title*, with: - **Name**: what your studio calls the game. The store's own title is read from the listing. - **Each platform the game is on**, one of three: **On Google Play** or **On the App Store** with the link (**Play Store link (Android)**, **App Store link**); **Not on Google Play yet** or **Not on the App Store yet** with a build and its draft listing; or **No build yet: a placeholder** with only the package name or bundle id. One title covers both platforms and has one app key. The last two are for a game [not on a store yet](#a-game-not-on-a-store-yet). - **Bundle id (optional)**: leave it empty unless the portal asks for it. NGA reads it from the App Store listing. Choose *Add the title*. NGA issues the app key at once and reads the store listing (title, category, icon, colors) as a job you can watch on the game's *Overview*, under *Profile*: from queued to done, usually within minutes, sometimes longer; the page refreshes itself while the job runs. The listing sets the colors of this game's banner, and the name and icon your other games show when they promote it. Until the first read finishes, the game's native placements get no fill. A store link belongs to one studio. A link already registered to another studio is refused; write to [hi@nga.network](mailto:hi@nga.network) if it is your game. If NGA finds no store listing at the link, the game's *Profile* says *No store listing found*; add the game again with the same link once it is listed. **A game registered on one platform** gets the other on its *Overview*: *Add Android* or *Add iOS*, with a store link or with a build and its draft listing, under the same app key. ### A game not on a store yet You can register a game before it launches, to test cross-promo with it, in one of two ways. **A build and its draft listing** (*Not on Google Play yet*, *Not on the App Store yet*). Give the **Package name** (Android) or **Bundle id** (iOS) as in the build; a **Build**: `.apk`, `.xapk`, `.apks` or `.apkm` on Android, `.ipa` on iOS, up to 512 MB (an App Bundle, `.aab`, is refused: download the signed universal APK from Play Console, *App bundle explorer*, *Downloads*, and upload that); and the listing the game will have: **Name on the listing**, **Category**, an **Icon**, and three to eight **Screenshots** (PNG, WebP or JPEG). NGA reads the build and the draft listing as it would a store listing; the build does not need your store signature, so a debug-signed or unsigned build is read like any other. The game is then **unlisted** on that platform, marked so in the titles list and on its *Overview*'s *Not on a store yet* card: - It is promoted only on your [registered test devices](https://nga.io/docs/sdk/testing/#register-a-test-device), never to players. There it fills your other games' placements like any of your games, so you can see its banner, and check your own game's integration, before either is in a store. - A tap on its banner or its full-screen ad is recorded and `onClicked` is called, but nothing opens: there is no store page yet. The impression and the click show in the report's test view. **A placeholder** (*No build yet: a placeholder*). Give only the package name or bundle id. The app key works at once, so you can build the game with it and add its placements now; its full-screen placements serve, its native placements get no fill, and it is shown in none of your games, until you upload a build with its listing under *Store and builds* (*Upload the build and its listing*), which makes it unlisted as above, or add its store link. Either keeps the app key. **At launch**, paste the store link in the *Not on a store yet* card and choose **Add the store link**. The game keeps its app key, so existing builds need no change. Players see the game in promotions once a store build runs with the SDK, while its *Promoted* switch is on; see [When a game is promoted](https://nga.io/docs/sdk/attribution/#when-a-game-is-promoted). ## The app key The game's *Overview* shows **App key and integration**: the key, with a copy button, and the `initialize` call for Unity, Android and iOS with the key filled in. [Initialize](https://nga.io/docs/sdk/initialize/) says where it goes. Once the game has a placement, **Hand it to your coding agent** beside it copies the [agent prompt](https://nga.io/docs/sdk/agents/) with this game's key, platforms and placements filled in. The *Overview* also shows: - **Profile**, per platform: what NGA read from the store listing or your builds (icon, store title, category, palette); whether the game *can host* the native banner (its colors are read) and *can be promoted* (its title and icon are read; it says so if its *Promoted* switch is off), each with what to do if not; and the reading job's state while one runs. - The game's *Switches*. Two are for cross-promo, each on from registration: **Shows cross-promo** (this game shows your other games) and **Promoted** (your other games can show this game). A game registered before there were two took its one *Cross-promo* switch's value on both. The titles list and the game's header show a badge for them: *both on*, *shows only*, *promoted only* or *off*. **Serving**: off stops all ad requests for this game; see [Stop serving](https://nga.io/docs/sdk/go-live/#stop-serving). *Store and builds* shows what NGA knows of each platform: the package name or bundle id, the App Store id, the packages your builds reported, and the signing certificates of your store-installed release builds. Under **Builds and their profiles** it lists every build you uploaded or that started with the SDK, newest first, each with its reading job, from queued to done or failed, and what the read found. **Upload a build** there when NGA should read a build the store does not have yet: `.apk`, `.xapk`, `.apks`, `.apkm` or `.ipa`, up to 512 MB, with store images if you like; NGA reads a build at most once every 14 days. A release build with another package name or bundle id gets no configuration; see [The app key](https://nga.io/docs/sdk/initialize/#the-app-key) on Initialize. ## Placements A placement is one place in your game where an NGA ad shows. Add it on the game's *Placements*, under *Add a placement*: - **Placement id**: you choose it, `plc_` and 3 to 64 lower-case letters, digits or `_`. You pass it to `loadAd`. - **Format** (cannot be changed later): - **Native**: the [native banner](https://nga.io/docs/sdk/native-cross-promo/). - **Interstitial** or **Rewarded**: [full-screen backfill](https://nga.io/docs/sdk/backfill/), shown when your mediation has no fill. Each placement then has: - **Prefetch**: native only, and on by default for a new native placement. The SDK loads the next ad ahead, so one is ready when the screen opens; turn it off per placement if you would rather load at the moment. Prefetch, like auto-reload, starts no load while the game is in the background: after a launch by a push, a job or a broadcast receiver, it loads when the game comes to the front. - **Auto-reload**: native only. The SDK loads again after each show. - **Caps** (below). - **Stop serving**, which turns the placement off without an app release. See [Stop serving](https://nga.io/docs/sdk/go-live/#stop-serving). Changes reach each install at its next start. ### Caps Caps count impressions per placement, never loads, so an ad that expires unseen costs nothing. A day is a rolling 24 hours. The defaults: | Format | Default caps per placement | | --- | --- | | Native | 3 a session, 10 a day | | Interstitial, Rewarded | 6 a day, at least 120 seconds apart | Set them per placement with *Per session*, *Per day* and *Seconds between*. A load at a cap fails with `NO_FILL / no_fill.cap` and sends no request; `retryAfterMillis` says when the cap reopens, and is null for a per-session cap, which reopens with the next session. A show still on screen counts against every cap. ## Promotion and creatives How a game appears when your other games promote it, per platform: | Where | What you set | See | | --- | --- | --- | | *Promotion* > *State* | read-only: *Waiting for the SDK*, *Pending* or *Promotable* | [Attribution](https://nga.io/docs/sdk/attribution/#when-a-game-is-promoted) | | *Promotion* > *Audience* | who plays the game on that platform: *General*, *Mixed* or *Children* | [Age and audience](https://nga.io/docs/sdk/privacy/#age-and-audience) | | *Promotion* > *Your MMP (optional)* | the *MMP click URL* and *MMP impression URL* of the game, for AppsFlyer or Adjust | [Attribution](https://nga.io/docs/sdk/attribution/#your-mmp) | | *Creatives* > *Native cross-promo* > *Copy* | the copy the banner shows for this game: NGA's proposals, to approve or reject, and your own (*Add the copy*, at most 50 characters, never naming another of your games); and a *Short name* of at most 20 characters when its store title is longer | [Native cross-promo](https://nga.io/docs/sdk/native-cross-promo/#what-the-banner-shows) | | *Creatives* > *Native cross-promo* > *Motif* | the cut-out that rests on the banner's corner: *Automatic* (NGA's pick, per host game, skipping one that is hard to see there), one of the cut-outs NGA read from the listing and your builds, or *No motif* | [Native cross-promo](https://nga.io/docs/sdk/native-cross-promo/#what-the-banner-is) | | *Creatives* > *Full-screen* | the video your other games' full-screen backfill plays for this game, and its endcard | [Full-screen backfill](https://nga.io/docs/sdk/backfill/#what-the-player-gets) | *Native cross-promo* also previews the banner as it draws, in NGA's default style and in each of your other games' colors (*Shown in*), stepping through the approved copy. A game you have not approved copy for is shown with "*name* — Play now". A game with no video is not shown full screen; it still appears in the banner, while its *Promoted* switch is on. ## Test devices *Test devices* holds your phones by name, each with one or more ids. *Add a device* takes a *Name (optional)* and the *Test-device id* from the SDK's log; or take an id from **Recent test installs not yet registered**, the games started in test mode in the last 7 days from an id you have not registered, with *Add to device…*. Each id is badged with what it covers, all your games on that device or one game ([which id covers what](https://nga.io/docs/sdk/testing/#register-a-test-device)), and *Move to device…* moves it to another device. Each device's page shows your games it ran, its recent ad requests with the reason for each no-fill, and its ad errors, so start there when a test device gets no ad. See [Register a test device](https://nga.io/docs/sdk/testing/#register-a-test-device). ## Report *Report* is [what you see in the report](https://nga.io/docs/sdk/attribution/#what-you-see-in-the-report), per host game, promoted game, placement, format and day; its *Test view* holds everything from test devices and test builds, which is in no report total. ## Next [Hand the integration to a coding agent](https://nga.io/docs/sdk/agents/), or [install the SDK](https://nga.io/docs/sdk/install/) yourself. # For AI coding agents Hand the integration to a coding agent such as Claude Code, Cursor or Copilot. Copy one prompt; the agent integrates the SDK up to a working test integration and asks you what only you can decide. *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/agents/* ## Before your agent starts Do these in the portal first; the agent cannot: 1. **Your studio is approved.** See [Sign up](https://nga.io/docs/sdk/portal/#sign-up). 2. **The game is registered**, from its store link or, before launch, from its package name or bundle id. See [Register a game](https://nga.io/docs/sdk/portal/#register-a-game). 3. **Its placements exist**: a *Native* placement for the banner, and an *Interstitial* or *Rewarded* placement for each full-screen backfill. See [Placements](https://nga.io/docs/sdk/portal/#placements). 4. **You have the app key and the placement ids.** The agent asks for them first, and stops if they do not exist yet. ## Copy the instructions Open your agent in your game's repository and paste this prompt. Fill in `{{APP_KEY}}`, `{{PLATFORM}}` and `{{PLACEMENTS}}` first, or leave them and the agent will ask. ````markdown # Integrate the NGA SDK into this game, up to a working test integration You are adding the NGA SDK 0.1.0, a preview version (the API can change until 1.0), to the game in this repository. NGA lets a studio promote its own games inside its other games: a native cross-promo banner the SDK shows at the bottom of the screen, and NGA's full-screen interstitial or rewarded ad, shown only when the game's own ad mediation has no fill. Your job ends at a working test integration. You do not take the game live. ## The rules - Read https://nga.io/docs/sdk/llms-full.txt in full before you change anything. It is the whole guide and API reference. Follow it exactly: the package coordinates, the version 0.1.0, every call and callback name. Where this prompt and the docs differ, the docs win; tell the developer. - Never invent an app key or a placement id, and never use the docs' examples (`app_YOURAPPKEY`, `plc_example_native`, `plc_example_interstitial`, `plc_example_rewarded`) in the game. - Keep the game's mediation in charge: never load NGA's full-screen placement except from the mediation's load-failed callback, and never show it while the mediation has an ad ready. - Change nothing in the game's mediation setup, ad units or consent flow except to add the NGA calls the docs give. - Exception: if the game does not retry a failed mediation load, add the retry the Full-screen backfill page requires, and tell the developer. - Do not edit files inside the NGA packages. - When this prompt says to ask the developer, ask and wait for the answer. Go on with the work that does not depend on it. ## 1. The ids from the NGA portal The integration needs these values from the developer's NGA portal (https://portal.nga.io): - App key: {{APP_KEY}} - Platform: {{PLATFORM}} - Placements, each with its format: {{PLACEMENTS}} If a value above is still a `{{…}}` placeholder, ask the developer for it before you write code that uses it. If they have no app key or no placements yet, stop. Tell them what is missing and send them to https://nga.io/docs/sdk/portal/ to get the studio approved, register the game, and create its placements (a Native placement for the banner; an Interstitial or Rewarded placement for each full-screen backfill). Continue when they have the ids. ## 2. Look before you change Find these in the repository and tell the developer what you found: - **The engine.** Unity (its version, and whether it builds for Android, iOS or both), native Android (Kotlin or Java, and the Gradle DSL), or native iOS (Swift or Objective-C, and how dependencies are managed). If it is none of these, stop: 0.1.0 supports Unity, Android and iOS only. - **The mediation SDK**: AppLovin MAX, Unity LevelPlay or Google AdMob, its version, and where the game loads and shows its interstitial and rewarded ads. Another mediation, or none: say so, and wire no backfill. - **The consent platform (CMP)**, if any (Google's UMP, or another that writes the IAB TCF or GPP keys), or the game's own consent screen, and where the game stores the player's answer. Whether the game has an age gate. - **What is at the bottom of the screen**: whether the game shows a banner ad there, on which screens, and through which class of its mediation; the banner yield (step 4) hides and shows that banner ad. - **A remove-ads purchase, and the game's languages.** Both decide when the native placement may load; the Native cross-promo page says how. ## 3. Install Install the SDK as the Install page says for this engine, at 0.1.0: the core library always, and the render library, since this game shows NGA ads. On Unity, add both packages at the same tag, and check the External Dependency Manager and the player settings the page lists (on Unity 2022.3, *Minify* for every Android build type you make, development builds included). Build the game and fix what fails before you go on; on Unity, the NGA build check names each problem. ## 4. Initialize, with consent from the CMP Initialize once, at start, exactly where and how the Initialize page says for this engine, with the app key from step 1: - The consent: take it from the CMP the way the Consent, age and privacy page says. With a CMP that writes the IAB keys, pass `NGAConsent.unknown()` and let the SDK read them. With the game's own consent screen, pass the answer it stored, and call `setConsent` wherever that screen saves a new answer. - In debug builds: test mode on and the log level at `DEBUG` before `initialize`, as the Initialize page shows. - Log the result of `onInitialized`. - On Unity, the bootstrap is a component on a GameObject in the first scene, as the Initialize page says. If you cannot add it to the scene yourself, write the component, make it run before the mediation's own start (its execution order), and ask the developer to add it. - **The banner yield**, if the game shows a banner ad of its own: right after `initialize`, register `NGASDK.setBannerYield(hide, restore)` (`SetBannerYield` in Unity) with the `hide` and `restore` the Native cross-promo page gives for this mediation and engine, so the game's banner ad leaves the bottom of the screen just before NGA's banner shows and comes back when the show ends. Keep the game's own banner pauses apart from it, as the page's examples do. A game with no banner ad registers none. ## 5. Full-screen backfill For each interstitial or rewarded NGA placement, wire NGA into the mediation's existing callbacks exactly as the Full-screen backfill page does for this mediation and engine, at the existing load-failed callback and show moment. Keep the game's own pause and resume around it, and leave the rest of the game's ad code as it is. ## 6. Ask the developer what only they can decide Ask these, all together, and wait for the answers: 1. **The native banner**: on which screens and at which moments it shows. It may show only where nothing else of the game's is at the bottom of the screen: the banner reaches 133 dp on a phone and 236 dp on a tablet above the bottom safe-area edge, across the full width, and the SDK does not move, shrink or report it, so whatever the player must see or tap at that moment must end above that height. The game's own banner ad steps aside through the banner yield (step 4). The Native cross-promo page says when not to load the banner (a player who bought remove-ads; a game running in another language). The game calls `close()` (`Close()` in Unity) before it shows anything of its own at the bottom, and when it leaves that screen. 2. **Children**: is the game directed at children, or does it ask players their age? A game that asks calls `setAge` from its age gate; the Consent, age and privacy page says how. 3. **Rewards**: for each rewarded placement, what the player gets. The game pays it from `onRewardResult`, keyed by the ad's `opportunityId`. Then wire the banner, the age and the rewards as the answers and the docs say. ## 7. The test integration Done means all of this holds, on a device or an emulator or simulator: 1. Test mode is on in the build you test. 2. You have found the test-device id the SDK prints at init (`test-device id (App Set ID): …` on Android, `test-device id (IDFV): …` on iOS) and given it to the developer, with the request to register it in the portal under Test devices. The line says what the id covers: an Android build not installed by Google Play (every build you sideload) has an id of its own in each game, so each such game's id needs registering. You cannot register it yourself. 3. The `DEBUG` init summary shows a successful init: the render library found (`render module: found`), the app key accepted by the server, and every placement you wired in the configuration. 4. Each placement you wired loads and shows a test ad on the registered device, or you name the reason it cannot, from the error's `code` and `detail` (no fill while testing: see "No fill while testing" on the Test your integration page). Where the game shows a banner ad, it disappears while NGA's banner shows and comes back after. 5. The Test your integration page's checklist passes for what you wired. Report each of the five: passed or not, and why. If you cannot run the game on a device, emulator or simulator, say so. Check what you can (both build targets compile; on Unity, the NGA build check passes), and tell the developer what to run and look for, for each of the five. ## What you do not do You do not take any go-live step: - You do not turn test mode off or change it for release builds. - You do not work through the release checklist. - You do not change anything in the portal: no switch, no serving, no store link, no placement and no test device. Hand these back to the developer, with a link to https://nga.io/docs/sdk/go-live/, when you report. ```` The same text is at [/docs/sdk/agent-prompt.md](https://nga.io/docs/sdk/agent-prompt.md). ## What the agent does It reads the whole guide and reference from one file, installs and initializes the SDK with the consent your consent platform holds, registers the [banner yield](https://nga.io/docs/sdk/native-cross-promo/#your-own-banner-ad) if your game shows a banner ad, wires [full-screen backfill](https://nga.io/docs/sdk/backfill/) into your mediation's existing load-failed callbacks, and turns test mode on for debug builds. It asks you four things: the app key and placement ids, if you did not fill them in; [where the banner shows](https://nga.io/docs/sdk/native-cross-promo/#where-the-banner-may-show), with its height kept clear, and when your game closes it; whether the game is [directed at children](https://nga.io/docs/sdk/privacy/#age-and-audience), or asks players their age; and the [reward](https://nga.io/docs/sdk/backfill/#rewarded) of each rewarded placement. It stops at a working test integration: test mode on, your test-device id printed for you to register, a successful `DEBUG` init summary, each placement it wired showing a test ad on your registered device (or the reason it cannot, often [no fill while testing](https://nga.io/docs/sdk/testing/#no-fill-while-testing)), and the [testing checklist](https://nga.io/docs/sdk/testing/#checklist) passed. You do the go-live steps yourself: test mode off in release builds, the [release checklist](https://nga.io/docs/sdk/go-live/#release-checklist), and checking the game's switches in the portal. ## These docs for agents Every page of these docs is also plain Markdown, for an agent or for you: - **Copy as Markdown**, beside each page's title, copies that page. *View as Markdown* opens it: each page's URL followed by `index.md`, such as [/docs/sdk/install/index.md](https://nga.io/docs/sdk/install/index.md). - **[/docs/sdk/llms.txt](https://nga.io/docs/sdk/llms.txt)** lists every page's Markdown, in the llms.txt convention. - **[/docs/sdk/llms-full.txt](https://nga.io/docs/sdk/llms-full.txt)** holds the whole guide and reference in one file, in the order of the sidebar. In the Markdown, every platform's code is under its own label, so an agent sees Unity, Android and iOS together. # Install Add the SDK from Maven Central and NGA's public repositories, at 0.1.0. Choose your engine; the choice holds on every page. *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/install/* ## What you add | Engine | From | Signals only | Signals and ads | | --- | --- | --- | --- | | Unity | Unity's Package Manager, from a Git URL | `network.nga.sdk` | `network.nga.sdk` and `network.nga.sdk-render` | | Android | Maven Central, group `network.nga`, through the BOM `nga-bom` | `nga-sdk` | `nga-sdk` and `nga-sdk-render` | | iOS | Swift Package Manager, `https://github.com/nga-io/nga-sdk-ios` | product `NGASDK` | product `NGASDKRender` | - **Use 0.1.0 for every coordinate on this page.** It reports `0.1.0`, from [`getSdkVersion()`](https://nga.io/docs/sdk/reference/ngasdk/#getsdkversion) and in what it sends to NGA. 0.1.0 is the build of its last release candidate, 0.1.0-rc.6, published again under the plain version. The candidates reported `0.1.0` too: only their coordinates and tags (the BOM's version, the Swift package's version, the Unity tag) carried `-rc.N`. - **Keep both libraries at the same version, from the same release.** Otherwise the render library is not used, and every ad call returns `RENDER_NOT_AVAILABLE / render.version_mismatch`; everything else works. Two builds of one version, two candidates or the release and a candidate other than its own build (0.1.0 is 0.1.0-rc.6's), both report 0.1.0, so from 0.1.0-rc.3 on each library also carries the id of the build it came from, and a core library at 0.1.0-rc.3 or later refuses a render library from another build the same way; in Unity, its build check fails such a pair first. An older core library catches neither. Move both packages to a new tag in one edit. - **No KDoc in the IDE:** the sources jar on Maven Central carries none; the API is on the [Reference](https://nga.io/docs/sdk/reference/) pages. ## Add the SDK **Unity (C#)** **1. An External Dependency Manager.** **Skip** if your project already has one (the MAX and Google Mobile Ads plugins include one; LevelPlay offers to install its Mobile Dependency Resolver when you open the project), or if the game is iOS-only. Otherwise add Unity's `com.unity.external-dependency-manager` 2.1.1 or later: *Window > Package Manager > + > Add package by name*. Google's `com.google.external-dependency-manager` (EDM4U) also works but is [deprecated](https://github.com/googlesamples/unity-jar-resolver). The NGA build check accepts any of these, as a package or as files under `Assets/`. Why: Unity's build does not read the SDK's Android dependencies from its packages. **2. The two packages, at one tag.** Requires Git on your machine. In *Window > Package Manager*, choose *+ > Add package from git URL…* and add the core library first, then the render library: `Add package from git URL` ```text https://github.com/nga-io/nga-sdk-unity.git?path=com.nga.sdk#v0.1.0 https://github.com/nga-io/nga-sdk-unity.git?path=com.nga.sdk-render#v0.1.0 ``` Or put both lines in `Packages/manifest.json` yourself, merged into your existing `dependencies`: `Packages/manifest.json` ```json { "dependencies": { "network.nga.sdk": "https://github.com/nga-io/nga-sdk-unity.git?path=com.nga.sdk#v0.1.0", "network.nga.sdk-render": "https://github.com/nga-io/nga-sdk-unity.git?path=com.nga.sdk-render#v0.1.0" } } ``` The folder in the URL (`com.nga.sdk`) is not the package name (`network.nga.sdk`); that is expected. Always add the core library: `network.nga.sdk-render` needs `network.nga.sdk` in your manifest at the same tag. **3. Player settings.** - *Android > Other Settings*: Minimum API Level 23 or later. - *Android > Publishing Settings > Minify*: on Unity 2022.3, turn on *Release* (`PlayerSettings.Android.minifyRelease`), and *Debug* (`PlayerSettings.Android.minifyDebug`) if you make development builds, and keep them on. Unity's default is off for both. With it off, a 2022.3 release build fails at the dexing step on the SDK's Kotlin libraries ([Troubleshooting](https://nga.io/docs/sdk/troubleshooting/#the-build-fails)), and the NGA build check stops a release or development build before Gradle runs, unless the project puts R8 8 or later on its build classpath (step 4). Unity 6 builds either way. - *Android > Publishing Settings*: turn on *Custom Main Gradle Template* and *Custom Gradle Properties Template*, so the External Dependency Manager can write the SDK's Android dependencies into them (leave them as they are if your mediation already turned them on). Then run *Assets > External Dependency Manager > Android Resolver > Resolve*. - *iOS > Other Settings*: Target minimum iOS Version 15.0 or later. Nothing else for iOS: the build embeds and signs the SDK's two frameworks, each with its own privacy manifest. - With `network.nga.sdk-render`, on every platform: *Resolution and Presentation > Render Over Native UI* off (`PlayerSettings.preserveFramebufferAlpha`). The native banner is drawn above your game's surface; with this setting on, the game would cover it. **4. Only for Unity 2022.3 Android builds with a recent mediation SDK** (MAX 13, LevelPlay 9.6 or later). Unity 2022.3 cannot dex these SDKs with its own tools. Turn on *Custom Gradle Settings Template* and add R8 to the build classpath, after the `pluginManagement { … }` block. Any R8 from 8.5.35 works; the snippet uses 8.7.18: `Assets/Plugins/Android/settingsTemplate.gradle` ```groovy buildscript { repositories { google(); mavenCentral() } dependencies { classpath 'com.android.tools:r8:8.7.18' } } ``` **Android (Kotlin)** **1. Maven Central.** Most projects have it. If yours does not, add it to the repositories in `settings.gradle.kts`: `settings.gradle.kts` ```kotlin dependencyResolutionManagement { repositories { google() mavenCentral() } } ``` **2. The SDK, through its BOM.** The BOM pins both libraries at one version, so you name the version once: `app/build.gradle.kts` ```kotlin dependencies { implementation(platform("network.nga:nga-bom:0.1.0")) implementation("network.nga:nga-sdk") implementation("network.nga:nga-sdk-render") // only if your game shows NGA ads } ``` In a Groovy `build.gradle`, the same lines are `implementation platform('network.nga:nga-bom:0.1.0')`, `implementation 'network.nga:nga-sdk'` and `implementation 'network.nga:nga-sdk-render'`. The libraries bring what they need at runtime: the Kotlin standard library (1.9 or later), Google's Play Install Referrer library and App Set. Add none of them yourself. `nga-sdk-render` requires `nga-sdk` at exactly its own version, so Gradle refuses a build that pulls a different core library beside it. **3. Check the app.** - `minSdk` is 23 or more. - Your merged manifest has `INTERNET` (required; without it the SDK sends nothing) and `ACCESS_NETWORK_STATE` (recommended). The SDK does not add them. Most ad or analytics SDKs do; if yours do not, declare them yourself. - Nothing else: the libraries carry their own R8 keep rules and need no other manifest entry. The SDK reads the advertising id only if your app ships Google's `play-services-ads-identifier` (most ad SDKs bring it); you need not add it for NGA. Java apps use the same libraries; see [Conventions](https://nga.io/docs/sdk/reference/#names-in-each-language). **iOS (Swift)** **1. Add the package.** In Xcode: *File > Add Package Dependencies…*, enter `https://github.com/nga-io/nga-sdk-ios`, and set the *Dependency Rule* to *Exact Version*, 0.1.0. Name it exactly, as the BOM and the Unity tag do: a range can move you to a newer version, and before 1.0 a minor version can change the API. The repository's tag is `v0.1.0`; Xcode and `Package.swift` name the version without the `v`. **2. Add one product to your app target:** - `NGASDKRender` if your game shows NGA ads. It brings `NGASDK` with it. - `NGASDK` if it does not. Xcode embeds and signs both frameworks. Each carries its own privacy manifest; see [What each library declares](https://nga.io/docs/sdk/privacy/#what-each-library-declares). If your game code is in a local Swift package, add the dependency to its `Package.swift`: `Package.swift` ```swift // swift-tools-version:5.9 import PackageDescription let package = Package( name: "Game", platforms: [.iOS(.v15)], dependencies: [ .package(url: "https://github.com/nga-io/nga-sdk-ios", exact: "0.1.0"), ], targets: [ .target(name: "Game", dependencies: [ .product(name: "NGASDKRender", package: "nga-sdk-ios"), // or "NGASDK" for signals only ]), ] ) ``` **3. Set the deployment target** to iOS 15.0 or later, and build with Xcode 26 or later. In your code, `import NGASDK`. You never import `NGASDKRender` or name anything from it: the SDK finds it at `initialize`. ## Unity build checks The Unity package fails an Android or iOS build when a setting would break the SDK on the device. The error starts with `NGA SDK: this build cannot run the NGA SDK.` and has one line per problem: | The build says | Fix | | --- | --- | | Minimum API Level is *n*; the NGA SDK needs API 23 or later | *Player > Android > Other Settings > Minimum API Level*: Android 6.0 (API level 23) or later | | Target minimum iOS Version is *n*; the NGA SDK needs iOS 15.0 or later | *Player > iOS > Other Settings > Target minimum iOS Version*: 15.0 or later | | The External Dependency Manager for Unity (`com.google.external-dependency-manager`) is not installed (Android builds) | add an External Dependency Manager (step 1 above), then *Assets > External Dependency Manager > Android Resolver > Resolve*; Unity's `com.unity.external-dependency-manager` satisfies the check too. Without it the build would succeed, but `initialize` would fail on the device because `kotlin-stdlib` is missing | | `network.nga.sdk` is at one version and `network.nga.sdk-render` at another | set both to the same tag in `Packages/manifest.json` | | `network.nga.sdk` carries native build *a* and `network.nga.sdk-render` build *b*: both are at one version, from two builds of it (two candidates, or the release and a candidate before 0.1.0-rc.6) | install both packages from one release: the same tag in both Git URLs | | Unity 2022.3 builds this Android release build (or development build) without minify | turn on *Player > Android > Publishing Settings > Minify > Release* (or *Debug*), as in step 3; or build with Unity 6 | | Render Over Native UI is on | *Player > Resolution and Presentation > Render Over Native UI*: off | ## Updating A new version changes one value: the tag in your two Unity Git URLs, the BOM's version on Android, or the exact version of the Swift package. Change both Unity lines in one edit, and let the Package Manager resolve both before you build: a core library older than 0.1.0-rc.3 does not notice a render library from a newer build of its version. Read the [changelog](https://nga.io/docs/sdk/changelog/) first. Going back to an older version is safe from 0.1.0-rc.3 on: where a newer SDK saved its files on the device in a shape the older one does not know, the older one sets them aside and starts as a new install there. ## Next [Initialize](https://nga.io/docs/sdk/initialize/) the SDK. # 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/). # Consent, age and privacy Tell the SDK what each player agreed to and, if your game asks, how old they are. It reads only what that allows, asks for no permission, and never shows a prompt. *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/privacy/* ## Consent Consent is two answers, each `UNKNOWN`, `GRANTED` or `DENIED`: | Field | Covers | | --- | --- | | `analytics` | the SDK's collection for your game: device details, advertising and vendor ids, the install referrer | | `adsPersonalization` | NGA's own use of the player's data across games, and, on Android, the advertising id on NGA's ad requests | Sessions, purchases, ad revenue and NGA's own ad events are recorded in every state, without identifiers where consent does not allow them. **`UNKNOWN` depends on where the player is.** Where the law requires consent (at 0.1.0: the EEA, the UK, Switzerland, South Korea and Quebec), `UNKNOWN` counts as `DENIED`. Everywhere else it counts as `GRANTED`. NGA decides the region on its server, so a new law is a server change, not an SDK release. ### Pass the player's answer Pass it in two places: - **At `initialize`**: what your consent screen last stored. The builder's value is applied field by field: `GRANTED` or `DENIED` replaces a value an earlier builder stored, and `UNKNOWN` keeps the stored value. So `NGAConsent.unknown()` at launch means "not known yet", never a withdrawal. - **With `setConsent`**, whenever the player answers or changes their mind. It replaces both fields (`UNKNOWN` included), is saved immediately (on Android, while the device's storage is unavailable, it applies at once and is saved as soon as storage is available; see [Calls before `initialize`](https://nga.io/docs/sdk/initialize/#calls-before-initialize)), and is never replaced by a later launch's builder. - **To withdraw**: `setConsent` with `DENIED`. **Unity (C#)** · `NGAPrivacy.cs` ```csharp using NGA; public static class NGAPrivacy { // Call when your consent screen or consent platform reports the player's choice. public static void OnConsentChanged(bool analyticsAllowed, bool adsPersonalizationAllowed) { NGASDK.SetConsent(new NGAConsent( analyticsAllowed ? NGAConsentState.Granted : NGAConsentState.Denied, adsPersonalizationAllowed ? NGAConsentState.Granted : NGAConsentState.Denied)); } // Call when your age gate answers. Only a game whose audience is Mixed needs this. public static void OnAgeGateAnswered(bool isChild) { NGASDK.SetAge(isChild ? NGAAgeState.Child : NGAAgeState.Adult); } } ``` **Android (Kotlin)** · `NGAPrivacy.kt` ```kotlin import network.nga.sdk.NGAAgeState import network.nga.sdk.NGAConsent import network.nga.sdk.NGAConsentState import network.nga.sdk.NGASDK object NGAPrivacy { // Call when your consent screen or consent platform reports the player's choice. fun onConsentChanged(analyticsAllowed: Boolean, adsPersonalizationAllowed: Boolean) { NGASDK.setConsent( NGAConsent( if (analyticsAllowed) NGAConsentState.GRANTED else NGAConsentState.DENIED, if (adsPersonalizationAllowed) NGAConsentState.GRANTED else NGAConsentState.DENIED, ), ) } // Call when your age gate answers. Only a game whose audience is Mixed needs this. fun onAgeGateAnswered(isChild: Boolean) { NGASDK.setAge(if (isChild) NGAAgeState.CHILD else NGAAgeState.ADULT) } } ``` **iOS (Swift)** · `NGAPrivacy.swift` ```swift import NGASDK enum NGAPrivacy { // Call when your consent screen or consent platform reports the player's choice. static func onConsentChanged(analyticsAllowed: Bool, adsPersonalizationAllowed: Bool) { NGASDK.setConsent(NGAConsent( analytics: analyticsAllowed ? .granted : .denied, adsPersonalization: adsPersonalizationAllowed ? .granted : .denied)) } // Call when your age gate answers. Only a game whose audience is Mixed needs this. static func onAgeGateAnswered(isChild: Bool) { NGASDK.setAge(isChild ? .child : .adult) } } ``` `getConsent()` returns the consent the SDK is using: your answer combined with the IAB TCF keys, the stricter one winning per field. ### Consent platforms **A platform that writes the IAB keys needs no code.** The SDK reads the IAB TCF, GPP and US Privacy keys from the standard store (`SharedPreferences` on Android, `UserDefaults` on iOS) at `initialize`, and again whenever they change. With such a platform, pass `NGAConsent.unknown()`, or only your own `analytics` answer, and let the keys decide. - **TCF** is applied on the device. Where it says GDPR applies, `analytics` follows your own purposes in the TC string, and `adsPersonalization` is `DENIED`. - **GPP and US Privacy** strings are sent to NGA as read. NGA honors a sale, sharing or targeted-ads opt-out, and Global Privacy Control. - **A game that treats "no answer yet" as denied** passes `DENIED` in both fields, not `unknown()`, while the platform has written nothing (an offline first launch, say), with the builder or with `setConsent` before `initialize`. The stricter of your answer and the keys wins per field, so the keys cannot widen it. Call `setConsent` with the platform's answer once it arrives. **A platform that writes no IAB keys** (some setups of Usercentrics and TrustArc, for example, and the consent screens used in South Korea and Quebec) needs `setConsent` with the player's answer. **Google Consent Mode v2** maps directly: `analytics_storage` to `analytics`, `ad_personalization` to `adsPersonalization`. ## Age and audience Each game has an **audience** per platform: *General*, *Mixed* or *Children*, the answer you give each store. > **In the portal (portal.nga.io).** > The game's *Promotion* > *Audience*, per platform: *Who plays it on Android* and *Who plays it on iOS*. | Audience | Who gets child treatment | | --- | --- | | *General* | players you set to `CHILD` with `setAge` | | *Mixed* | players you set to `CHILD`, and players whose age you have not set | | *Children* | every player | NGA's server applies the same rule to every request, from the audience as it is set in the portal and the age your game reported, so a change of audience does not wait for each device's next configuration. Only a *Mixed* game needs `setAge`: - Call it from your age gate: `CHILD` for a player under the child age of their local law and your store declarations (under 13 in the US; 13 to 16 in the EEA, by country), otherwise `ADULT`. - With no age gate, every player is treated as a child, and the SDK logs one warning at init. - AdMob's child-directed or under-age-of-consent tags map to `setAge(CHILD)` for that player, or to the *Children* audience for the whole game. **Under child treatment:** - The SDK reads no advertising or vendor id, and no device details beyond the coarse ones any ad needs. - NGA ads are chosen from context only. - On iOS the banner and full-screen ads still show, but their installs are not measured. - On Android, every ad request gets no fill until NGA completes Google Play's Families self-certification. - Consent can never widen child treatment. iOS games in the App Store's Kids Category are not supported in 0.1.0. Games with a *Children* or *Mixed* audience outside that category, and every Android game, are. ## App Tracking Transparency The SDK never shows the ATT prompt; showing it is your game's choice. - **Without the prompt, or when the player declines,** the SDK reads no IDFA. Everything else works the same; NGA's ads on iOS use no IDFA in 0.1.0. - **When the player allows tracking** and `analytics` is not denied, the SDK reads the IDFA and sends it to `optin.nga.io` (the tracking domain in its privacy manifest) once, and again only if it changes. The SDK reads the ATT status when your game becomes active, and again 1 s, 2.5 s and 5 s later while it is not determined, so an answer given in your prompt or in Settings applies within seconds. ## What each library declares **Unity (C#)** A Unity build declares the same as the native libraries for its target: see the Android or iOS tab. On iOS, Xcode merges both frameworks' privacy manifests into your app's privacy report, as for a native app. **Android (Kotlin)** | Library | Adds to your merged manifest | | --- | --- | | `nga-sdk` | nothing of its own. Its two dependencies add: the Play Install Referrer library's normal install-time permission `com.google.android.finsky.permission.BIND_GET_INSTALL_REFERRER_SERVICE`, and from App Set, Google Play services' `GoogleApiActivity` (not exported) and its version `meta-data` | | `nga-sdk-render` | NGA's full-screen ad `Activity`, not exported | The SDK uses a permission only if your app already holds it: | Permission | Used for | Without it | | --- | --- | --- | | `INTERNET` | every request to NGA | nothing is sent | | `ACCESS_NETWORK_STATE` | the network type, and sending queued events when the network returns | network type is not reported | | `com.google.android.gms.permission.AD_ID` | the advertising id (API 33+); declared by Google's ads-identifier library | no advertising id | | `READ_PHONE_STATE` or `READ_BASIC_PHONE_STATE` | the cellular network generation | not reported | | `com.android.vending.BILLING` | seeing Play purchases; declared by Play Billing | no purchase capture | The SDK adds no `` element and does not read which apps are installed. **iOS (Swift)** Each framework carries its own `PrivacyInfo.xcprivacy`, which Xcode merges into your app's privacy report. | | `NGASDK` | `NGASDKRender` | | --- | --- | --- | | `NSPrivacyTracking` | `true`, for the IDFA of players who allow tracking | `false` | | `NSPrivacyTrackingDomains` | `optin.nga.io` | none | | Accessed APIs (reason) | `UserDefaults` (CA92.1) | disk space (E174.1), file timestamp (C617.1) | | Collected data types | Device ID (used for tracking), User ID, Product Interaction, Advertising Data, Purchase History, Other Diagnostic Data, Other Data Types, Coarse Location | Advertising Data, Product Interaction | Every collected type is linked to the user, and only Device ID is used for tracking. The SDK declares no usage string and no entitlement. **Required-reason APIs the manifest does not declare.** Besides `UserDefaults`, `NGASDK` reads the device's uptime (`ProcessInfo.systemUptime`, `mach_continuous_time`), its total and free disk space (`volumeTotalCapacityKey`, `volumeAvailableCapacityForImportantUsage`) and the list of enabled keyboards (`UITextInputMode.activeInputModes`), as device details sent to NGA under analytics consent. Apple lists these among its required-reason APIs, and none of its approved reasons covers sending the values to a server, so the manifest does not declare them: a declared reason would not be true. NGA has accepted this review risk for 0.1.0 rather than declare a reason it does not meet. If App Review asks your game about any of them, send Apple's message to [hi@nga.network](mailto:hi@nga.network); NGA answers it with you. ### Hosts the SDK contacts | Host | For | | --- | --- | | `api.nga.io` | initialization, events, ad requests | | `optin.nga.io` | iOS only: the IDFA link, only for players who allow tracking | | `cdn.nga.io` | ads' files: icons, images and videos | All three are HTTPS on port 443, TLS 1.2 or later. Nothing goes to any other host. The SDK fetches ads' files on any connection; on cellular, NGA serves smaller video files. ## Store privacy forms These tables are guidance for filling in Google Play's Data safety form and Apple's App Privacy details for the NGA SDK's part of your game. Confirm them against your own game and with your own counsel; they are not legal advice. Every row is linked to the user, since each travels with an install id, and all data is encrypted in transit. | What the SDK sends | Google Play Data safety | Purposes | | --- | --- | --- | | Device identifiers: an install id, the advertising id, App Set ID and Android ID | Device or other IDs | app functionality (the App Set ID: test devices, and finding a player's data for a deletion request), analytics, advertising, fraud prevention | | Your customer user id, when you set one | User IDs | analytics | | Sessions and NGA ad events | App interactions | analytics, advertising | | Ad revenue from your mediation | App interactions | analytics | | Purchases | Purchase history | analytics | | Device, network and performance details, and device settings such as language | Diagnostics | analytics, fraud prevention | | Region, from the IP address, on NGA's server | Approximate location | analytics, advertising | | What the SDK sends | Apple App Privacy | Purposes | | --- | --- | --- | | Device identifiers: an install id, the IDFV, and the IDFA for players who allow tracking | Device ID | analytics, third-party advertising; used for tracking (the IDFA only) | | Your customer user id, when you set one; the App Store's app transaction id | User ID | analytics | | Sessions and NGA ad events | Product Interaction, Advertising Data | analytics, third-party advertising | | Ad revenue from your mediation | Advertising Data | analytics | | Purchases | Purchase History | analytics | | Device, network and performance details | Other Diagnostic Data | analytics, app functionality | | Device settings such as language | Other Data Types | analytics | | Region, from the IP address, on NGA's server | Coarse Location | analytics, third-party advertising | If your iOS game never shows the ATT prompt, the SDK never reads the IDFA, but `NGASDK`'s manifest still declares tracking. Ask NGA ([hi@nga.network](mailto:hi@nga.network)) for current guidance on answering App Privacy in that case. ## Opting out and deletion To opt a player out, pass `DENIED` with `setConsent`. There is no per-signal opt-out and no switch that turns the SDK off in code. 0.1.0 has no deletion call. To have one player's data deleted, a member of your studio writes from their address to [data-deletion-request@nga.network](mailto:data-deletion-request@nga.network), naming the game and one id of the player that your game can read: - the customer user id your game passes with `setCustomerUserId`; - or the device's vendor id, the IDFV on iOS (`identifierForVendor`) or the App Set ID on Android (from Google Play services), which covers that device's installs of all your games that share it: on iOS, your games in one developer account; on Android, your games from one Google Play developer account, installed from Google Play. The SDK's own install id is never shown to your game or the player, so a request cannot name it. NGA confirms the request and deletes that player's data from its servers within 30 days during the preview; its backups age out within about 35 days. NGA finds a player only by an id it kept from them. It keeps none for a player who has only played under child treatment, or who never granted analytics consent (where the law requires consent, `UNKNOWN` counts as not granted), outside a debug build in test mode; a request for such a player finds nothing, and NGA's reply says so. # Native cross-promo Load a native placement and show it. The SDK slides up a banner for one of your other games, in your game's colors, at the bottom of the screen. You do not place or size it. *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/native-cross-promo/* ## What the banner is A native banner, centered on the bottom safe-area edge. It shows one of your other games: icon, name, one line, and an arrow. A cut-out from that game sits at the top-left corner and a close button at the top-right. Both rise a little above the banner. | | Phone | Tablet | | --- | --- | --- | | Size | 320 × 100 dp | 728 × 180 dp | | Maximum height, from the bottom safe-area edge | 133 dp | 236 dp | | Used when | any other window, a phone in landscape included | the window is at least 744 dp wide and its shorter side at least 600 dp | The size is chosen at `show`, from the window then, and kept until the banner closes. The banner's bottom edge sits on the bottom safe-area edge (Android: the window's bottom system-bar inset; iOS: the safe area's bottom), and the cut-out rises above it, 33 dp on the phone size and 56 dp on the tablet size: the banner reaches 133 dp or 236 dp above that edge, and its soft shadow a few dp more. It is centered, 320 or 728 dp wide, and the cut-out and the close reach about 10 dp past its sides. The phone-size banner keeps 8 dp from the window's sides where the window has room; on a window under 336 dp wide that margin shrinks, to none at 320 dp, and the cut-out and the close move in just enough that the window's edge never cuts them. On iOS the same numbers are points. **Keeping that area clear at the break is your layout.** The SDK does not move, shrink or report the banner, and nothing of your game's sits there while it shows: a bottom bar, a button row or a banner ad's 50 dp slot is shorter than the banner and would be covered. Lay the screen out so that whatever the player must see or tap at that moment ends above the height in the table. - **It slides up** in 300 ms and slides back down when it closes; with the system's reduce-motion setting on, it fades in and out in place instead. - **A tap anywhere on the banner** opens the promoted game's store page (on iOS, as a sheet over your game). Taps in the first 300 ms after it lands do nothing. - **A tap opens nothing** on a game [not on a store yet](https://nga.io/docs/sdk/portal/#a-game-not-on-a-store-yet) or on one already installed on the device: only your test devices are shown either, never a player's. - **The close button** is its own target, 48 dp square, and always works. A touch outside the banner and its close reaches your game. - **Your code never names a game:** it loads a placement, and NGA's server picks which of your other games with *Promoted* on fills it each time. > **In the portal (portal.nga.io).** > A *Native* placement in this game, on its *Placements*. See [Placements](https://nga.io/docs/sdk/portal/#placements). ## Where the banner may show The banner draws over whatever is at the bottom of the screen, and it cannot be moved. Nothing of your game's sits there while it shows: - **Show it only where the bottom is empty:** game over, level complete, pause, or a menu with its buttons higher up. The area is the [height to keep clear](#what-the-banner-is), across the full width. - **Your own banner ad steps aside through the [banner yield](#your-own-banner-ad):** the SDK hides it just before NGA's banner draws and shows it again when the show ends. Register the yield once; your banner ad then needs no other rule. Covering a network's banner would break its policies. - **Close it first** (`close()`, Unity `Close()`) before you put anything of your own there: a "continue" bar, a keyboard, a panel. One banner shows at a time in your app. ### Players who should not see it In two cases, do not load the native placement; keep your own content in that slot: - **A player who bought remove-ads.** The banner carries the AD label, so a player who paid to see no ads should not see it. Full-screen backfill needs nothing: NGA's ad is loaded only where your mediation's would have been shown, so your game's own remove-ads rule covers those moments. - **A game running in another language.** The banner's text is English-only in this release. The examples below check both before they load. ## Your own banner ad If your game shows a banner ad of its own, register a **banner yield** once, at start: two callbacks the SDK runs around every native banner show. A game with no banner ad registers none. | | The SDK | Your code | | --- | --- | --- | | `hide` | called once per show, on the main thread (Unity: the game thread), just before NGA's banner is added, once the show's other checks have passed. The banner follows one frame later, so your layout settles first | hides the banner ad's view and pauses its refresh. The ad stays loaded: never destroy or reload it for this | | `restore` | called exactly once for each `hide`, after NGA's banner is removed, whatever ended the show: the player's close, your `close()`, the screen going away, the window shrinking, or a `hide` that failed | shows the banner ad again and resumes its refresh, if your game still wants the banner there. Resume refresh whenever the banner is allowed now, not only when it was refreshing at `hide` | - **A tap on NGA's banner** opens the store over your game and leaves the banner up; your banner ad stays hidden until the show ends. - **A `hide` that throws** (in Unity: throws, or is not back within a second) refuses the show: `onShowFailed` with `INVALID_SHOW_TARGET / show.target.yield_failed`, the ad stays `READY`, and `restore` is still called. A throw from `restore` is not caught: it is your game's. - **Register it once**, right after `initialize`, with [`setBannerYield`](https://nga.io/docs/sdk/reference/ngasdk/#setbanneryield); the pair is held until a later call replaces it. Both `null` clears it; one `null` alone is ignored with a warning. A registration before `initialize` is kept too. - **With no yield registered**, the first native show in the process logs one `WARN`, `NGACrossPromo: no banner yield registered`, and NGA's banner draws over whatever is there. A game that shows no banner ad can ignore that line. - **Unity.** `hide` runs on the game thread and the SDK waits for it at most a second: hide the banner and pause its refresh, nothing else. One example per mediation and engine. Each keeps your game's own banner pauses apart from the yield, in one small class: a resume of your game's cannot bring the banner ad back while NGA's banner is up, and a banner ad created during a yield starts hidden and paused. **AppLovin MAX** **Unity (C#)** · `MaxBannerYield.cs` ```csharp using System; using NGA; // Your banner ad's side of the yield, beside the code that owns the banner ad. One instance for the game. public sealed class MaxBannerYield { readonly string adUnitId; // your MAX banner ad unit readonly Func wanted; // your game's own answer: the banner belongs on this screen right now public MaxBannerYield(string adUnitId, Func wanted) { this.adUnitId = adUnitId; this.wanted = wanted; } // NGA's banner is up and the banner ad is out of its way. While it is true, your own code does not call ShowBanner. public bool Yielded { get; private set; } // Register once, right after NGASDK.Initialize. public void Register() => NGASDK.SetBannerYield(Hide, Restore); // The SDK, on the game thread, just before NGA's banner draws. Not guarded: a throw here must reach the SDK, which refuses the show. void Hide() { Yielded = true; MaxSdk.HideBanner(adUnitId); MaxSdk.StopBannerAutoRefresh(adUnitId); // the ad stays loaded, never destroyed or reloaded for this } // The SDK, once per Hide, when the show ends, however it ended. void Restore() { if (!Yielded) return; Yielded = false; MaxSdk.StartBannerAutoRefresh(adUnitId); // refresh resumes whatever the banner's state at Hide if (wanted()) MaxSdk.ShowBanner(adUnitId); // and it is shown again if your game still wants it there } } ``` **Android (Kotlin)** · `MaxBannerYield.kt` ```kotlin import android.view.View import com.applovin.mediation.ads.MaxAdView import network.nga.sdk.NGASDK // Your banner ad's side of the yield, beside the code that owns the banner ad. One instance for the app. class MaxBannerYield { private var banner: MaxAdView? = null // NGA's banner is up and the banner ad is out of its way. var yielded = false private set // Your game's own wish: refresh, unless it paused the banner (MAX's banner refreshes from its first load). private var refreshWanted = true // Register once, right after NGASDK.initialize. fun register() = NGASDK.setBannerYield(Runnable { hide() }, Runnable { restore() }) // Your banner ad's view when you create it, null when you destroy it. A view attached during a yield starts hidden and paused. fun attach(view: MaxAdView?) { banner = view if (view != null && yielded) { view.visibility = View.GONE view.stopAutoRefresh() } } // Your game's own pauses, kept apart from the yield: the Activity going to the background, the banner no longer allowed. fun pause() { refreshWanted = false banner?.stopAutoRefresh() } fun resume() { refreshWanted = true if (!yielded) banner?.startAutoRefresh() // while yielded, the banner stays paused until restore } // The SDK, on the main thread, just before NGA's banner draws. private fun hide() { yielded = true banner?.let { it.visibility = View.GONE it.stopAutoRefresh() // the ad stays loaded, never destroyed or reloaded for this } } // The SDK, once per hide, when the show ends, however it ended. private fun restore() { if (!yielded) return yielded = false banner?.let { it.visibility = View.VISIBLE if (refreshWanted) it.startAutoRefresh() // refresh resumes if your game wants the banner now } } } ``` **iOS (Swift)** · `MaxBannerYield.swift` ```swift import UIKit import AppLovinSDK import NGASDK // Your banner ad's side of the yield, beside the code that owns the banner ad. One instance for the app. final class MaxBannerYield { private var banner: MAAdView? // NGA's banner is up and the banner ad is out of its way. private(set) var yielded = false // Your game's own wish: refresh, unless it paused the banner (MAX's banner refreshes from its first load). private var refreshWanted = true // Register once, right after NGASDK.initialize. func register() { NGASDK.setBannerYield(hide: { [weak self] in self?.hide() }, restore: { [weak self] in self?.restore() }) } // Your banner ad's view when you create it, nil when you remove it. A view attached during a yield starts hidden and paused. func attach(_ view: MAAdView?) { banner = view if let view, yielded { view.isHidden = true view.stopAutoRefresh() } } // Your game's own pauses, kept apart from the yield: the app going to the background, the banner no longer allowed. func pause() { refreshWanted = false banner?.stopAutoRefresh() } func resume() { refreshWanted = true if !yielded { banner?.startAutoRefresh() } // while yielded, the banner stays paused until restore } // The SDK, on the main thread, just before NGA's banner draws. private func hide() { yielded = true banner?.isHidden = true banner?.stopAutoRefresh() // the ad stays loaded, never destroyed or reloaded for this } // The SDK, once per hide, when the show ends, however it ended. private func restore() { guard yielded else { return } yielded = false banner?.isHidden = false if refreshWanted { banner?.startAutoRefresh() } // refresh resumes if your game wants the banner now } } ``` **Unity LevelPlay** **Unity (C#)** · `LevelPlayBannerYield.cs` ```csharp using System; using NGA; using Unity.Services.LevelPlay; // Your banner ad's side of the yield, beside the code that owns the banner ad. One instance for the game. public sealed class LevelPlayBannerYield { readonly Func wanted; // your game's own answer: the banner has loaded and belongs on this screen right now LevelPlayBannerAd banner; // your banner ad, from Attach public LevelPlayBannerYield(Func wanted) { this.wanted = wanted; } // NGA's banner is up and the banner ad is out of its way. While it is true, your own code does not call ShowAd. public bool Yielded { get; private set; } // Register once, right after NGASDK.Initialize. public void Register() => NGASDK.SetBannerYield(Hide, Restore); // Your banner ad when you create it, null when you destroy it. A banner made during a yield starts hidden and paused. public void Attach(LevelPlayBannerAd ad) { banner = ad; if (ad == null || !Yielded) return; ad.HideAd(); ad.PauseAutoRefresh(); } // The SDK, on the game thread, just before NGA's banner draws. Not guarded: a throw here must reach the SDK, which refuses the show. void Hide() { Yielded = true; if (banner == null) return; banner.HideAd(); banner.PauseAutoRefresh(); // the ad stays loaded, never destroyed or reloaded for this } // The SDK, once per Hide, when the show ends, however it ended. void Restore() { if (!Yielded) return; Yielded = false; if (banner == null) return; banner.ResumeAutoRefresh(); // refresh resumes whatever the banner's state at Hide if (wanted()) banner.ShowAd(); // and it is shown again if your game still wants it there } } ``` **Android (Kotlin)** · `LevelPlayBannerYield.kt` ```kotlin import android.view.View import com.unity3d.mediation.banner.LevelPlayBannerAdView import network.nga.sdk.NGASDK // Your banner ad's side of the yield, beside the code that owns the banner ad. One instance for the app. class LevelPlayBannerYield { private var banner: LevelPlayBannerAdView? = null // NGA's banner is up and the banner ad is out of its way. var yielded = false private set // Your game's own wish: refresh, unless it paused the banner (LevelPlay's banner refreshes from its first load). private var refreshWanted = true // Register once, right after NGASDK.initialize. fun register() = NGASDK.setBannerYield(Runnable { hide() }, Runnable { restore() }) // Your banner ad's view when you create it, null when you destroy it. A view attached during a yield starts hidden and paused. fun attach(view: LevelPlayBannerAdView?) { banner = view if (view != null && yielded) { view.visibility = View.GONE view.pauseAutoRefresh() } } // Your game's own pauses, kept apart from the yield: the Activity going to the background, the banner no longer allowed. fun pause() { refreshWanted = false banner?.pauseAutoRefresh() } fun resume() { refreshWanted = true if (!yielded) banner?.resumeAutoRefresh() // while yielded, the banner stays paused until restore } // The SDK, on the main thread, just before NGA's banner draws. private fun hide() { yielded = true banner?.let { it.visibility = View.GONE it.pauseAutoRefresh() // the ad stays loaded, never destroyed or reloaded for this } } // The SDK, once per hide, when the show ends, however it ended. private fun restore() { if (!yielded) return yielded = false banner?.let { it.visibility = View.VISIBLE if (refreshWanted) it.resumeAutoRefresh() // refresh resumes if your game wants the banner now } } } ``` **iOS (Swift)** · `LevelPlayBannerYield.swift` ```swift import UIKit import IronSource import NGASDK // Your banner ad's side of the yield, beside the code that owns the banner ad. One instance for the app. final class LevelPlayBannerYield { private var banner: LPMBannerAdView? // NGA's banner is up and the banner ad is out of its way. private(set) var yielded = false // Your game's own wish: refresh, unless it paused the banner (LevelPlay's banner refreshes from its first load). private var refreshWanted = true // Register once, right after NGASDK.initialize. func register() { NGASDK.setBannerYield(hide: { [weak self] in self?.hide() }, restore: { [weak self] in self?.restore() }) } // Your banner ad's view when you create it, nil when you remove it. A view attached during a yield starts hidden and paused. func attach(_ view: LPMBannerAdView?) { banner = view if let view, yielded { view.isHidden = true view.pauseAutoRefresh() } } // Your game's own pauses, kept apart from the yield: the app going to the background, the banner no longer allowed. func pause() { refreshWanted = false banner?.pauseAutoRefresh() } func resume() { refreshWanted = true if !yielded { banner?.resumeAutoRefresh() } // while yielded, the banner stays paused until restore } // The SDK, on the main thread, just before NGA's banner draws. private func hide() { yielded = true banner?.isHidden = true banner?.pauseAutoRefresh() // the ad stays loaded, never destroyed or reloaded for this } // The SDK, once per hide, when the show ends, however it ended. private func restore() { guard yielded else { return } yielded = false banner?.isHidden = false if refreshWanted { banner?.resumeAutoRefresh() } // refresh resumes if your game wants the banner now } } ``` **Google AdMob** **Unity (C#)** · `AdMobBannerYield.cs` ```csharp using System; using GoogleMobileAds.Api; using NGA; // Your banner ad's side of the yield, beside the code that owns the banner ad. One instance for the game. public sealed class AdMobBannerYield { readonly Func wanted; // your game's own answer: the banner has loaded and belongs on this screen right now BannerView banner; // your banner ad, from Attach public AdMobBannerYield(Func wanted) { this.wanted = wanted; } // NGA's banner is up and the banner ad is out of its way. While it is true, your own code does not call Show. public bool Yielded { get; private set; } // Register once, right after NGASDK.Initialize. public void Register() => NGASDK.SetBannerYield(Hide, Restore); // Your banner ad when you create it, null when you destroy it. A banner made during a yield starts hidden. public void Attach(BannerView ad) { banner = ad; if (ad != null && Yielded) ad.Hide(); } // The SDK, on the game thread, just before NGA's banner draws. Not guarded: a throw here must reach the SDK, which refuses the show. // Hide() also pauses the AdView on Android; on iOS the plugin has no pause, and hiding is all there is to do. void Hide() { Yielded = true; banner?.Hide(); // the ad stays loaded, never destroyed or reloaded for this } // The SDK, once per Hide, when the show ends, however it ended. void Restore() { if (!Yielded) return; Yielded = false; if (banner != null && wanted()) banner.Show(); // shown again if your game still wants it there } } ``` **Android (Kotlin)** · `AdMobBannerYield.kt` ```kotlin import android.view.View import com.google.android.gms.ads.AdView import network.nga.sdk.NGASDK // Your banner ad's side of the yield, beside the code that owns the banner ad. One instance for the app. class AdMobBannerYield { private var banner: AdView? = null // NGA's banner is up and the banner ad is out of its way. var yielded = false private set // Your game's own wish: refresh, unless it paused the banner (AdMob's banner refreshes from its first load). private var refreshWanted = true // Register once, right after NGASDK.initialize. fun register() = NGASDK.setBannerYield(Runnable { hide() }, Runnable { restore() }) // Your banner ad's view when you create it, null when you destroy it. A view attached during a yield starts hidden and paused. fun attach(view: AdView?) { banner = view if (view != null && yielded) { view.visibility = View.GONE view.pause() } } // Your game's own pauses, kept apart from the yield: the Activity going to the background, the banner no longer allowed. fun pause() { refreshWanted = false banner?.pause() } fun resume() { refreshWanted = true if (!yielded) banner?.resume() // while yielded, the banner stays paused until restore } // The SDK, on the main thread, just before NGA's banner draws. private fun hide() { yielded = true banner?.let { it.visibility = View.GONE it.pause() // stops its refresh; the ad stays loaded, never destroyed or reloaded for this } } // The SDK, once per hide, when the show ends, however it ended. private fun restore() { if (!yielded) return yielded = false banner?.let { it.visibility = View.VISIBLE if (refreshWanted) it.resume() // refresh resumes if your game wants the banner now } } } ``` **iOS (Swift)** · `AdMobBannerYield.swift` ```swift import UIKit import GoogleMobileAds import NGASDK // Your banner ad's side of the yield, beside the code that owns the banner ad. One instance for the app. final class AdMobBannerYield { private var banner: BannerView? // NGA's banner is up and the banner ad is out of its way. private(set) var yielded = false // Register once, right after NGASDK.initialize. func register() { NGASDK.setBannerYield(hide: { [weak self] in self?.hide() }, restore: { [weak self] in self?.restore() }) } // Your banner ad's view when you create it, nil when you remove it. A view attached during a yield starts hidden. func attach(_ view: BannerView?) { banner = view if yielded { view?.isHidden = true } } // The SDK, on the main thread, just before NGA's banner draws. AdMob's iOS banner has no refresh pause: hiding it is all there is to do. private func hide() { yielded = true banner?.isHidden = true // the ad stays loaded, never destroyed or reloaded for this } // The SDK, once per hide, when the show ends, however it ended. private func restore() { guard yielded else { return } yielded = false banner?.isHidden = false } } ``` The calls each mediation gives, which the examples use and nothing else: | Mediation | `hide` | `restore` | | --- | --- | --- | | AdMob | Android: `AdView` to `GONE`, `pause()`. iOS: `BannerView.isHidden`. Unity: `BannerView.Hide()`, which pauses the `AdView` on Android | Android: `VISIBLE`, `resume()`. iOS: `isHidden = false`. Unity: `Show()` | | LevelPlay | Android `LevelPlayBannerAdView`, iOS `LPMBannerAdView`: hidden, `pauseAutoRefresh()`. Unity `LevelPlayBannerAd`: `HideAd()`, `PauseAutoRefresh()` | shown, `resumeAutoRefresh()`. Unity: `ResumeAutoRefresh()`, `ShowAd()` | | MAX | Android `MaxAdView`, iOS `MAAdView`: hidden, `stopAutoRefresh()`. Unity: `MaxSdk.HideBanner`, `StopBannerAutoRefresh` | shown, `startAutoRefresh()`. Unity: `StartBannerAutoRefresh`, `ShowBanner` | ## What the banner shows - **Your game's style.** The banner takes your game's colors, read from its store listing (or draft listing) at registration. On some native Android games it also takes the shape of the game's own panels and buttons; every other game gets NGA's standard banner in its colors, and a game whose colors NGA cannot read gets NGA's default style. - **Before NGA first reads your game's listing,** its native placements get `NO_FILL`. | Text | Comes from | Limit | | --- | --- | --- | | Name | the *Short name* you gave in the portal, else the store title | a short name is at most 20 characters; a longer name is cut with an ellipsis | | Line | one of the copy lines you approved under *Creatives*; with none approved, "*name* — Play now" | 50 characters | The text is in the system font, in English, left to right. > **In the portal (portal.nga.io).** > The promoted game's *Creatives* > *Native cross-promo*: approve or write its copy, pick its motif (the cut-out on the banner's corner) or leave it to *Automatic*, and give it a *Short name* of at most 20 characters when its store title is longer. The preview there shows the banner in each of your games' colors. ## Load and show Load when the screen opens. When `onLoaded` is called, call `show` with the screen: on Android the Activity, on iOS the view controller, in Unity nothing. A load that finds no ad calls `onFailed`, and the bottom of the screen stays empty. - **One-screen games.** If a level's end is a moment, not a screen, call `loadAd` at that moment and `show` in `onLoaded`. Ignore an `onLoaded` that arrives after the moment has passed. With *Prefetch* on, `onLoaded` is called immediately, with an ad already loaded. - **Which view controller (iOS).** Pass the one that shows your game. In SpriteKit, Metal or a single-scene game this is usually the key window's root view controller. In SwiftUI it is the `UIHostingController` that hosts your game's view. **Unity (C#)** · `GameOverScreen.cs` ```csharp using UnityEngine; using NGA; // On your game-over screen's root object. Nothing else is at the bottom of this screen. public class GameOverScreen : MonoBehaviour, NGAAdLoadCallback, NGAAdShowListener { const string GameOverPromo = "plc_example_native"; NGAAd promoAd; // from its load until its show ends void OnEnable() { if (RemoveAdsOwned() || !GameInEnglish()) return; // see Players who should not see it NGASDK.LoadAd(GameOverPromo, this); } // The banner stays on screen across your scenes and panels until it is closed. void OnDisable() { ClosePromo(); } // Call this before your game shows anything of its own at the bottom of the screen. public void ClosePromo() { promoAd?.Close(); } // NGAAdLoadCallback public void OnLoaded(NGAAd ad) { // promoAd is kept after a refused show, and the next LoadAd hands back that same ad: show it again. if (this == null || !isActiveAndEnabled || (promoAd != null && promoAd != ad) || !ad.IsReady()) return; promoAd = ad; ad.Show(this); // the SDK adds the banner over the bottom of the screen and slides it up } public void OnFailed(string placementId, NGAError error) { } // no fill: the bottom stays empty public void OnExpired(NGAAd ad) { if (promoAd != null && promoAd.OpportunityId == ad.OpportunityId) promoAd = null; } // NGAAdShowListener public void OnShowStarted(NGAAd ad) { } // the impression counted public void OnClicked(NGAAd ad) { } // the store is opening public void OnRewardResult(NGAAd ad, NGARewardResult result) { } // never for the banner public void OnCompleted(NGAAd ad, NGAShowCompletion completion) { } public void OnClosed(NGAAd ad) { promoAd = null; } // the player's close, Close(), or the screen going away public void OnShowFailed(NGAAd ad, NGAError error) { if (!ad.IsReady()) promoAd = null; // a refused show leaves the ad ready: the next OnEnable shows it } // Your game's own code. bool RemoveAdsOwned() { return false; } bool GameInEnglish() { return true; } } ``` **Android (Kotlin)** · `GameOverActivity.kt` ```kotlin import android.app.Activity import android.os.Bundle import network.nga.sdk.NGAAd import network.nga.sdk.NGAAdLoadCallback import network.nga.sdk.NGAAdShowListener import network.nga.sdk.NGAError import network.nga.sdk.NGASDK import network.nga.sdk.NGAShowCompletion // Your game-over screen. Nothing else is at the bottom of its layout. class GameOverActivity : Activity(), NGAAdLoadCallback, NGAAdShowListener { private var promoAd: NGAAd? = null // from its load until its show ends override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // setContentView(…): your game-over layout if (removeAdsOwned() || !gameInEnglish()) return // see Players who should not see it NGASDK.loadAd(GAME_OVER_PROMO, this) } override fun onResume() { super.onResume() promoAd?.takeIf { it.isReady() }?.show(this, this) // a show refused while this screen was paused } // Call this before your game shows anything of its own at the bottom of the screen. fun closePromo() { promoAd?.close() // slides the banner down; onClosed follows } // NGAAdLoadCallback override fun onLoaded(ad: NGAAd) { if (isDestroyed || promoAd != null || !ad.isReady()) return promoAd = ad ad.show(this, this) // the SDK adds the banner over the bottom of this screen and slides it up } override fun onFailed(placementId: String, error: NGAError) {} // no fill: the bottom stays empty override fun onExpired(ad: NGAAd) { if (promoAd === ad) promoAd = null } // NGAAdShowListener override fun onShowStarted(ad: NGAAd) {} // the impression counted override fun onCompleted(ad: NGAAd, completion: NGAShowCompletion) {} override fun onClosed(ad: NGAAd) { // the player's close, close(), or this screen going away if (promoAd === ad) promoAd = null } override fun onShowFailed(ad: NGAAd, error: NGAError) { if (promoAd === ad && !ad.isReady()) promoAd = null // a refused show leaves the ad ready: onResume shows it } // Your game's own code. private fun removeAdsOwned(): Boolean = false private fun gameInEnglish(): Boolean = true companion object { const val GAME_OVER_PROMO = "plc_example_native" } } ``` **iOS (Swift)** · `GameOverViewController.swift` ```swift import UIKit import NGASDK // Your game-over screen. Nothing else is at the bottom of its view. final class GameOverViewController: UIViewController, NGAAdLoadCallback, NGAAdShowListener { private static let gameOverPromo = "plc_example_native" private var promoAd: NGAAd? // from its load until its show ends override func viewDidLoad() { super.viewDidLoad() // Your game-over content goes here. if removeAdsOwned() || !gameInEnglish() { return } // see Players who should not see it NGASDK.loadAd(Self.gameOverPromo, callback: self) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) if let ad = promoAd, ad.isReady { ad.show(from: self, listener: self) } // loaded before this screen was on screen } // Call this before your game shows anything of its own at the bottom of the screen. func closePromo() { promoAd?.close() // slides the banner down; onClosed follows } // NGAAdLoadCallback func onLoaded(_ ad: NGAAd) { guard isViewLoaded, promoAd == nil, ad.isReady else { return } promoAd = ad ad.show(from: self, listener: self) // the SDK adds the banner over the bottom of this view and slides it up } func onFailed(placementId: String, error: NGAError) {} // no fill: the bottom stays empty func onExpired(_ ad: NGAAd) { if promoAd === ad { promoAd = nil } } // NGAAdShowListener func onShowStarted(_ ad: NGAAd) {} // the impression counted func onCompleted(_ ad: NGAAd, completion: NGAShowCompletion) {} func onClosed(_ ad: NGAAd) { // the player's close, close(), or this screen going away if promoAd === ad { promoAd = nil } } func onShowFailed(_ ad: NGAAd, error: NGAError) { if promoAd === ad && !ad.isReady { promoAd = nil } // a refused show leaves the ad ready: viewDidAppear shows it } // Your game's own code. private func removeAdsOwned() -> Bool { false } private func gameInEnglish() -> Bool { true } } ``` **A screen that cannot present yet.** `show` needs the screen in front. Otherwise it fails with `ACTIVITY_NOT_RESUMED`, the ad stays `READY`, and you show it again when the screen is back, as `onResume` and `viewDidAppear` do above. Every refusal is in [Show lifecycle](#show-lifecycle). **The examples register the screen as the load callback**, so the SDK can keep a closed screen in memory for up to 30 minutes if its ad is never shown. That is harmless for most games; to avoid it, see [Callback ownership](https://nga.io/docs/sdk/reference/#callback-ownership). **Unity.** The banner is added over the Unity player's view, above all Unity UI, and Unity's Activity and view controller last the whole game: the banner stays on screen across your scenes and panels until it is closed. Close it when you leave the screen you showed it on, as `OnDisable` does above. Keep *Render Over Native UI* off; the build check enforces it. **Single-Activity games (Android).** If your screens are Compose destinations or fragments in one Activity, the Activity does not go away with the screen, so neither does the banner. Close it when the screen leaves (for example, when its composable leaves the composition), as the Unity example does in `OnDisable`. ### The banner and a full-screen ad on one screen If one screen shows the banner and runs [full-screen backfill](https://nga.io/docs/sdk/backfill/), give each its own callback object: the backfill examples keep theirs in `InterstitialBackfill` and `RewardedBackfill`, so the screen itself can be the banner's, as above. Or keep one set of callbacks and branch on `ad.placementId`. An object declared inside the screen holds the screen as the screen itself would; an app-wide object does not. **When both come at one moment**, such as a level's end, show the full-screen ad first and the banner after its `onClosed`: a banner cannot open over a full-screen ad (see [Show lifecycle](#show-lifecycle)). ## Show lifecycle The show callbacks, for the banner: | Callback | When | | --- | --- | | `onShowStarted` | the impression counted: once the banner has landed, at least half of it visible for a second, its screen in front and the device's screen on | | `onClicked` | each tap on the banner (it opens the store). A tap before the impression counts the impression first | | `onCompleted(COMPLETED)`, then `onClosed` | the show ended after its impression | | `onClosed` alone | the show ended before its impression counted | | `onShowFailed` | the show could not start; `error` says why, and nothing follows | The banner never gets `onRewardResult`. Every show ends exactly once, with one `onClosed` or one `onShowFailed`; the full order is on [Callbacks](https://nga.io/docs/sdk/reference/callbacks/#ngaadshowlistener). **When `show` is refused**, `onShowFailed` is called and the ad stays `READY`. Show it again when the cause is gone: | Cause | Error | Show again when | | --- | --- | --- | | The screen is not in front (Android: the Activity not resumed, or finishing; iOS: the view controller not in a window or presenting something, or the app not active), or a full-screen ad is in front | `ACTIVITY_NOT_RESUMED / show.activity.not_resumed` | the screen is back (`onResume`, `viewDidAppear`, as in the examples), or the full-screen ad has closed | | Another banner is on screen | `ALREADY_SHOWING / show.already_showing.banner` | that banner has closed | | The window is under 320 × 133 dp (the phone size's banner, and the cut-out above it), such as a narrow split-screen | `INVALID_SHOW_TARGET / show.target.window_too_small` | the window is bigger | | Your [banner yield](#your-own-banner-ad)'s `hide` threw (in Unity: threw, or was not back within a second). `restore` was called | `INVALID_SHOW_TARGET / show.target.yield_failed` | `hide` is fixed; the ad stays ready | A loaded banner can start showing for 30 minutes. After that it has expired, `isReady()` is false, and `show` fails with `EXPIRED`: load again. See [`NGAAd`](https://nga.io/docs/sdk/reference/values/#ngaad). **While it shows:** | Event | Result | | --- | --- | | The player taps the banner | the store opens over your game; the banner stays up, and your banner ad stays hidden | | The player taps the close, or you call `close()` | the show ends; the banner slides down and is removed, and your banner ad is restored. `close()` on an ad that is not showing does nothing | | Its screen goes away: on Android the Activity is destroyed, a system recreate included; on iOS the view controller is dismissed, popped or released | the show ends with `onClosed`. A recreated screen loads a new banner | | The window shrinks below 320 × 133 dp, for example into a split-screen half | the show ends | | A rotation or resize, on iOS or on an Android Activity that handles its own configuration changes (Unity's does) | the banner moves to the new bottom center, at the size it started with | | Another screen or a full-screen ad covers it | the banner waits underneath, and its impression timer pauses | | It has been on screen a long time | nothing: expiry applies only before the show starts | **For the next banner, call `loadAd` again with a callback**; the shown ad has released the old one. With *Auto-reload* on, the SDK loads the next ad as soon as a show ends, so on a screen that stays open the next `loadAd` gets its `onLoaded` immediately. Caps keep it in bounds (by default 3 banners a session and 10 a day per placement, see [Caps](https://nga.io/docs/sdk/portal/#caps)); at a cap, loads fail with `NO_FILL / no_fill.cap`. ## Next Add [full-screen backfill](https://nga.io/docs/sdk/backfill/), or [test](https://nga.io/docs/sdk/testing/) the banner on a registered device. # Full-screen backfill When your mediation has no interstitial or rewarded ad, show NGA's in that moment. Your mediation always comes first, so NGA never takes a moment it could fill. *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/backfill/* ## The rule Your code keeps the rule, because the SDK cannot see your mediation. A moment is a point where your game would show an ad. 1. **Load NGA's placement only from your mediation's load-failed callback.** Never ahead of a failure. 2. **At the moment of the show, your mediation comes first.** If its ad is ready, show it. Show NGA's only while your mediation's latest load has failed and NGA's ad `isReady()`. 3. **Keep retrying your mediation.** When it loads again, it has the next moment. > **In the portal (portal.nga.io).** > An *Interstitial* placement and a *Rewarded* placement on the game's *Placements*; prefetch and auto-reload stay off for both, so the SDK itself loads nothing ahead of a mediation failure. A format is fixed when its placement is created. See [Placements](https://nga.io/docs/sdk/portal/#placements). A remove-ads purchase needs no NGA code here: NGA's ad is loaded only where your mediation's would have been shown, so your game's own remove-ads rule covers those moments. ## The order at startup 1. **Initialize NGA before your mediation**, as on [Initialize](https://nga.io/docs/sdk/initialize/), or [later](https://nga.io/docs/sdk/initialize/#initializing-later) once your consent platform has answered, but still before the mediation. NGA's capture of MAX and LevelPlay revenue starts there, so an ad your mediation shows right after is recorded. 2. **Initialize your mediation** as its own documentation says, in the same place or in your first screen. 3. **Create and load the mediation's ads after its init is done** (*Init is done when*, below). The examples load in the screen's `onCreate`, `viewDidLoad` or `Start`, which works only if init finished before the screen opened. If the same screen starts the mediation: - Create the mediation's ad and load it the first time in the mediation's init callback. - Check that the ad exists before you show or destroy it. The show moment can come before init is done. The examples' helpers belong to the screen and are its load callbacks, so the SDK holds the screen, through them, for up to 30 minutes; for a screen that closes often, keep the helper app-wide ([Callback ownership](https://nga.io/docs/sdk/reference/#callback-ownership)). For the native banner and a backfill on one screen, see [Native cross-promo](https://nga.io/docs/sdk/native-cross-promo/#the-banner-and-a-full-screen-ad-on-one-screen). ## What the player gets - **One of your other games' videos**, full screen, with its endcard if you supplied one. - **A way out.** A close button always appears, even when an ad stalls or fails to play, and back works on Android once the close is available. An interstitial's close appears within seconds; a rewarded ad's, when the reward is earned. - **The store only on a tap.** Nothing opens the store without the player's tap. - **Your game, as it was.** The ad runs in NGA's own full-screen Activity or view controller. Its sound follows [`setMuted`](https://nga.io/docs/sdk/reference/ngasdk/#setmuted-ismuted), and your audio session is restored when it closes. > **In the portal (portal.nga.io).** > A game appears in full-screen backfill once its video is under its *Creatives*, while its *Promoted* switch is on. Video: MP4 or MOV, H.264 or HEVC (with AAC sound, if it has any), portrait or landscape but not square, 6 to 60 seconds, at most 200 MB. Endcard: one still PNG, JPEG or WebP image (not animated), at most 1 MB. ## Pause and resume Pause your game's loop, timers and sound right before you call `show`. Resume on `onClosed` or `onShowFailed`, the two callbacks that end every show. Do not wait for `onShowStarted`. It marks the impression, and is called a second or more after `show`, or never if the impression does not count. | Unity | on Android | on iOS | | --- | --- | --- | | While the ad is in front | Unity pauses itself | nothing is paused | | The show's callbacks arrive | after the ad closes, in their original order | during the ad | | `OnApplicationPause` | `true` as the ad opens, `false` as it closes. That resume is not a return from the background | — | Either way, pause the game yourself before `Show`, and do not depend on any callback arriving while the ad is on screen. ## Your mediation Initialize your mediation as its own documentation says, before the first load. The examples were built and checked with these versions, which are not the oldest that work: they use only the calls shown (for LevelPlay, its ad-unit API, `LevelPlayInterstitialAd` and `LevelPlayRewardedAd`), so an older version with those calls compiles the same code. | | AppLovin MAX | Unity LevelPlay | Google AdMob | | --- | --- | --- | --- | | Android | `com.applovin:applovin-sdk:13.7.0` | `com.unity3d.ads-mediation:mediation-sdk:9.7.0` | `com.google.android.gms:play-services-ads:25.5.0` (see [Requirements](https://nga.io/docs/sdk/#requirements)) | | iOS | the `AppLovinSDK` Swift package 13.7.0 | `LevelPlay-Swift-Package` 9.7.0 (module `IronSource`) | the `GoogleMobileAds` Swift package 13.12.0 | | Unity | the MAX Unity plugin 8.6.6 | `com.unity.services.levelplay` 9.6.0 | the Google Mobile Ads Unity plugin 11.6.0 | | Init is done when | Android: `AppLovinSdk.getInstance(context).initialize(config, listener)` completes. iOS: `ALSdk.shared().initialize(with:completionHandler:)` completes. Unity: `MaxSdkCallbacks.OnSdkInitializedEvent` has fired | its init success: `LevelPlayInitListener.onInitSuccess` (Android), `LevelPlay.initWith`'s completion with no error (iOS), `LevelPlay.OnInitSuccess` (Unity) | `MobileAds.initialize` completes | | Setup guide | [Unity](https://support.applovin.com/en/max/unity/overview/integration/) · [Android](https://support.applovin.com/en/max/android/overview/integration/) · [iOS](https://support.applovin.com/en/max/ios/overview/integration/) | [Unity](https://docs.unity.com/en-us/grow/levelplay/sdk/unity/interstitial-integration) · [Android](https://docs.unity.com/en-us/grow/levelplay/sdk/android/interstitial-integration) · [iOS](https://docs.unity.com/en-us/grow/levelplay/sdk/ios/interstitial-integration) | [Unity](https://developers.google.com/admob/unity/quick-start) · [Android](https://developers.google.com/admob/android/quick-start) · [iOS](https://developers.google.com/admob/ios/quick-start) | | Rewarded ad to wire | Unity: `MaxSdkCallbacks.Rewarded.OnAdLoadedEvent` and `OnAdLoadFailedEvent`. Android: `MaxRewardedAd.getInstance(adUnitId)` with a `MaxRewardedAdListener`. iOS: `MARewardedAd.shared(withAdUnitIdentifier:)` | `LevelPlayRewardedAd` (Unity, Android), `LPMRewardedAd` (iOS) | `RewardedAd.load` | | Note | the Android example uses MAX 13's one-argument `MaxInterstitialAd(adUnitId)`; AppLovin's page still shows the two-argument form, deprecated since 13.6 | — | on iOS, Google Mobile Ads 13.12 reports paid events to the ad's `FullScreenContentDelegate`, so the example's delegate forwards them to [ad revenue](https://nga.io/docs/sdk/revenue/#ad-revenue-from-your-mediation) | ## Interstitial Choose your mediation; the choice holds on this page. Each example is one screen that owns the mediation's interstitial and hands NGA's half to `InterstitialBackfill`, the helper after the examples, which keeps [the rule](#the-rule). **AppLovin MAX** **Unity (C#)** · `MaxBackfill.cs` ```csharp using System; using System.Collections; using UnityEngine; public class MaxBackfill : MonoBehaviour { const string MaxAdUnit = "YOUR_MAX_INTERSTITIAL_AD_UNIT"; readonly InterstitialBackfill nga = new InterstitialBackfill(); // InterstitialBackfill.cs, below int maxRetry; void Start() // once MAX has initialized (MaxSdkCallbacks.OnSdkInitializedEvent has fired) { MaxSdkCallbacks.Interstitial.OnAdLoadedEvent += OnMaxLoaded; MaxSdkCallbacks.Interstitial.OnAdLoadFailedEvent += OnMaxLoadFailed; MaxSdkCallbacks.Interstitial.OnAdHiddenEvent += OnMaxHidden; MaxSdkCallbacks.Interstitial.OnAdDisplayFailedEvent += OnMaxDisplayFailed; MaxSdk.LoadInterstitial(MaxAdUnit); } void OnDestroy() { MaxSdkCallbacks.Interstitial.OnAdLoadedEvent -= OnMaxLoaded; MaxSdkCallbacks.Interstitial.OnAdLoadFailedEvent -= OnMaxLoadFailed; MaxSdkCallbacks.Interstitial.OnAdHiddenEvent -= OnMaxHidden; MaxSdkCallbacks.Interstitial.OnAdDisplayFailedEvent -= OnMaxDisplayFailed; } // Call at the moment your game would show an interstitial. public void ShowInterstitial() { if (MaxSdk.IsInterstitialReady(MaxAdUnit)) { PauseGame(); MaxSdk.ShowInterstitial(MaxAdUnit); // the mediation always comes first } else if (!nga.TryShow(PauseGame, AfterNga)) ContinueGame(); // MAX has no fill and NGA has nothing ready } // MAX void OnMaxLoaded(string adUnitId, MaxSdkBase.AdInfo info) { nga.OnMediationLoaded(); maxRetry = 0; } void OnMaxLoadFailed(string adUnitId, MaxSdkBase.ErrorInfo error) { if (this == null) return; nga.OnMediationLoadFailed(); maxRetry++; StartCoroutine(RetryMax((float)Math.Pow(2, Math.Min(6, maxRetry)))); // AppLovin's backoff } void OnMaxHidden(string adUnitId, MaxSdkBase.AdInfo info) { MaxSdk.LoadInterstitial(MaxAdUnit); ResumeGame(); ContinueGame(); } void OnMaxDisplayFailed(string adUnitId, MaxSdkBase.ErrorInfo error, MaxSdkBase.AdInfo info) { MaxSdk.LoadInterstitial(MaxAdUnit); ResumeGame(); ContinueGame(); } IEnumerator RetryMax(float seconds) { yield return new WaitForSecondsRealtime(seconds); if (this != null) MaxSdk.LoadInterstitial(MaxAdUnit); } void AfterNga() { if (this == null) return; ResumeGame(); ContinueGame(); } // Your game's own code. void PauseGame() { } void ResumeGame() { } void ContinueGame() { } } ``` **Android (Kotlin)** · `MaxBackfillActivity.kt` ```kotlin import android.app.Activity import android.os.Bundle import android.os.Handler import android.os.Looper import com.applovin.mediation.MaxAd import com.applovin.mediation.MaxAdListener import com.applovin.mediation.MaxError import com.applovin.mediation.ads.MaxInterstitialAd import kotlin.math.min import kotlin.math.pow // MAX is initialized, as AppLovin's documentation says, before this screen opens. class MaxBackfillActivity : Activity(), MaxAdListener { private val handler = Handler(Looper.getMainLooper()) private val nga = InterstitialBackfill() // InterstitialBackfill.kt, below private lateinit var maxAd: MaxInterstitialAd private var maxRetry = 0 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) maxAd = MaxInterstitialAd(MAX_AD_UNIT) maxAd.setListener(this) maxAd.loadAd() } override fun onDestroy() { handler.removeCallbacksAndMessages(null) maxAd.destroy() super.onDestroy() } // Call at the moment your game would show an interstitial. fun showInterstitial() { if (maxAd.isReady) { pauseGame() maxAd.showAd(this) // the mediation always comes first } else if (!nga.tryShow(this, ::pauseGame, ::afterNga)) { continueGame() // MAX has no fill and NGA has nothing ready } } // MaxAdListener override fun onAdLoaded(ad: MaxAd) { nga.onMediationLoaded() maxRetry = 0 } override fun onAdLoadFailed(adUnitId: String, error: MaxError) { if (isDestroyed) return nga.onMediationLoadFailed() maxRetry++ val delayMs = 1000L * 2.0.pow(min(6, maxRetry)).toLong() // AppLovin's backoff handler.postDelayed({ maxAd.loadAd() }, delayMs) } override fun onAdDisplayed(ad: MaxAd) {} override fun onAdClicked(ad: MaxAd) {} override fun onAdHidden(ad: MaxAd) { maxAd.loadAd() resumeGame() continueGame() } override fun onAdDisplayFailed(ad: MaxAd, error: MaxError) { maxAd.loadAd() resumeGame() continueGame() } private fun afterNga() { if (isDestroyed) return resumeGame() continueGame() } // Your game's own code. private fun pauseGame() {} private fun resumeGame() {} private fun continueGame() {} companion object { const val MAX_AD_UNIT = "YOUR_MAX_INTERSTITIAL_AD_UNIT" } } ``` **iOS (Swift)** · `MaxBackfillViewController.swift` ```swift import UIKit import AppLovinSDK // MAX is initialized, as AppLovin's documentation says, before this screen opens. final class MaxBackfillViewController: UIViewController, MAAdDelegate { private let maxAd = MAInterstitialAd(adUnitIdentifier: "YOUR_MAX_INTERSTITIAL_AD_UNIT") private let nga = InterstitialBackfill() // InterstitialBackfill.swift, below private var maxRetry = 0.0 override func viewDidLoad() { super.viewDidLoad() maxAd.delegate = self maxAd.load() } // Call at the moment your game would show an interstitial. func showInterstitial() { if maxAd.isReady { pauseGame() maxAd.show() // the mediation always comes first } else if !nga.tryShow(from: self, pauseGame: pauseGame, afterAd: afterNga) { continueGame() // MAX has no fill and NGA has nothing ready } } // MAAdDelegate func didLoad(_ ad: MAAd) { nga.onMediationLoaded() maxRetry = 0 } func didFailToLoadAd(forAdUnitIdentifier adUnitIdentifier: String, withError error: MAError) { nga.onMediationLoadFailed() maxRetry += 1 let delay = pow(2.0, min(6.0, maxRetry)) // AppLovin's backoff DispatchQueue.main.asyncAfter(deadline: .now() + delay) { [weak self] in self?.maxAd.load() } } func didDisplay(_ ad: MAAd) {} func didClick(_ ad: MAAd) {} func didHide(_ ad: MAAd) { maxAd.load() resumeGame() continueGame() } func didFail(toDisplay ad: MAAd, withError error: MAError) { maxAd.load() resumeGame() continueGame() } private func afterNga() { resumeGame() continueGame() } // Your game's own code. private func pauseGame() {} private func resumeGame() {} private func continueGame() {} } ``` **Unity LevelPlay** **Unity (C#)** · `LevelPlayBackfill.cs` ```csharp using System; using System.Collections; using UnityEngine; using Unity.Services.LevelPlay; public class LevelPlayBackfill : MonoBehaviour { const string LevelPlayAdUnit = "YOUR_LEVELPLAY_INTERSTITIAL_AD_UNIT"; readonly InterstitialBackfill nga = new InterstitialBackfill(); // InterstitialBackfill.cs, below LevelPlayInterstitialAd levelPlayAd; int levelPlayRetry; // Call once LevelPlay.OnInitSuccess has fired. public void StartAds() { levelPlayAd = new LevelPlayInterstitialAd(LevelPlayAdUnit); levelPlayAd.OnAdLoaded += OnLevelPlayLoaded; levelPlayAd.OnAdLoadFailed += OnLevelPlayLoadFailed; levelPlayAd.OnAdClosed += OnLevelPlayClosed; levelPlayAd.OnAdDisplayFailed += OnLevelPlayDisplayFailed; levelPlayAd.LoadAd(); } void OnDestroy() { levelPlayAd?.DestroyAd(); } // Call at the moment your game would show an interstitial. public void ShowInterstitial() { if (levelPlayAd != null && levelPlayAd.IsAdReady()) { PauseGame(); levelPlayAd.ShowAd(); // the mediation always comes first } else if (!nga.TryShow(PauseGame, AfterNga)) ContinueGame(); // LevelPlay has no fill and NGA has nothing ready } // LevelPlay void OnLevelPlayLoaded(LevelPlayAdInfo info) { nga.OnMediationLoaded(); levelPlayRetry = 0; } void OnLevelPlayLoadFailed(LevelPlayAdError error) { if (this == null) return; nga.OnMediationLoadFailed(); levelPlayRetry++; StartCoroutine(RetryLevelPlay((float)Math.Pow(2, Math.Min(6, levelPlayRetry)))); } void OnLevelPlayClosed(LevelPlayAdInfo info) { levelPlayAd.LoadAd(); ResumeGame(); ContinueGame(); } void OnLevelPlayDisplayFailed(LevelPlayAdInfo info, LevelPlayAdError error) { levelPlayAd.LoadAd(); ResumeGame(); ContinueGame(); } IEnumerator RetryLevelPlay(float seconds) { yield return new WaitForSecondsRealtime(seconds); if (this != null) levelPlayAd.LoadAd(); } void AfterNga() { if (this == null) return; ResumeGame(); ContinueGame(); } // Your game's own code. void PauseGame() { } void ResumeGame() { } void ContinueGame() { } } ``` **Android (Kotlin)** · `LevelPlayBackfillActivity.kt` ```kotlin import android.app.Activity import android.os.Bundle import android.os.Handler import android.os.Looper import com.unity3d.mediation.LevelPlayAdError import com.unity3d.mediation.LevelPlayAdInfo import com.unity3d.mediation.interstitial.LevelPlayInterstitialAd import com.unity3d.mediation.interstitial.LevelPlayInterstitialAdListener import kotlin.math.min import kotlin.math.pow // LevelPlay has initialized (LevelPlayInitListener.onInitSuccess) before this screen opens. class LevelPlayBackfillActivity : Activity(), LevelPlayInterstitialAdListener { private val handler = Handler(Looper.getMainLooper()) private val nga = InterstitialBackfill() // InterstitialBackfill.kt, below private lateinit var levelPlayAd: LevelPlayInterstitialAd private var levelPlayRetry = 0 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) levelPlayAd = LevelPlayInterstitialAd(LEVELPLAY_AD_UNIT) levelPlayAd.setListener(this) levelPlayAd.loadAd() } override fun onDestroy() { handler.removeCallbacksAndMessages(null) super.onDestroy() } // Call at the moment your game would show an interstitial. fun showInterstitial() { if (levelPlayAd.isAdReady()) { pauseGame() levelPlayAd.showAd(this) // the mediation always comes first } else if (!nga.tryShow(this, ::pauseGame, ::afterNga)) { continueGame() // LevelPlay has no fill and NGA has nothing ready } } // LevelPlayInterstitialAdListener override fun onAdLoaded(adInfo: LevelPlayAdInfo) { nga.onMediationLoaded() levelPlayRetry = 0 } override fun onAdLoadFailed(error: LevelPlayAdError) { if (isDestroyed) return nga.onMediationLoadFailed() levelPlayRetry++ val delayMs = 1000L * 2.0.pow(min(6, levelPlayRetry)).toLong() handler.postDelayed({ levelPlayAd.loadAd() }, delayMs) } override fun onAdDisplayed(adInfo: LevelPlayAdInfo) {} override fun onAdDisplayFailed(error: LevelPlayAdError, adInfo: LevelPlayAdInfo) { levelPlayAd.loadAd() resumeGame() continueGame() } override fun onAdClicked(adInfo: LevelPlayAdInfo) {} override fun onAdClosed(adInfo: LevelPlayAdInfo) { levelPlayAd.loadAd() resumeGame() continueGame() } override fun onAdInfoChanged(adInfo: LevelPlayAdInfo) {} private fun afterNga() { if (isDestroyed) return resumeGame() continueGame() } // Your game's own code. private fun pauseGame() {} private fun resumeGame() {} private fun continueGame() {} companion object { const val LEVELPLAY_AD_UNIT = "YOUR_LEVELPLAY_INTERSTITIAL_AD_UNIT" } } ``` **iOS (Swift)** · `LevelPlayBackfillViewController.swift` ```swift import UIKit import IronSource // LevelPlay has initialized (LevelPlay.initWith's completion with no error) before this screen opens. final class LevelPlayBackfillViewController: UIViewController, LPMInterstitialAdDelegate { private let levelPlayAd = LPMInterstitialAd(adUnitId: "YOUR_LEVELPLAY_INTERSTITIAL_AD_UNIT") private let nga = InterstitialBackfill() // InterstitialBackfill.swift, below private var levelPlayRetry = 0.0 override func viewDidLoad() { super.viewDidLoad() levelPlayAd.setDelegate(self) levelPlayAd.loadAd() } // Call at the moment your game would show an interstitial. func showInterstitial() { if levelPlayAd.isAdReady() { pauseGame() levelPlayAd.showAd(viewController: self, placementName: nil) // the mediation always comes first } else if !nga.tryShow(from: self, pauseGame: pauseGame, afterAd: afterNga) { continueGame() // LevelPlay has no fill and NGA has nothing ready } } // LPMInterstitialAdDelegate func didLoadAd(with adInfo: LPMAdInfo) { nga.onMediationLoaded() levelPlayRetry = 0 } func didFailToLoadAd(withAdUnitId adUnitId: String, error: Error) { nga.onMediationLoadFailed() levelPlayRetry += 1 let delay = pow(2.0, min(6.0, levelPlayRetry)) DispatchQueue.main.asyncAfter(deadline: .now() + delay) { [weak self] in self?.levelPlayAd.loadAd() } } func didDisplayAd(with adInfo: LPMAdInfo) {} func didFailToDisplayAd(with adInfo: LPMAdInfo, error: Error) { levelPlayAd.loadAd() resumeGame() continueGame() } func didCloseAd(with adInfo: LPMAdInfo) { levelPlayAd.loadAd() resumeGame() continueGame() } private func afterNga() { resumeGame() continueGame() } // Your game's own code. private func pauseGame() {} private func resumeGame() {} private func continueGame() {} } ``` **Google AdMob** **Unity (C#)** · `AdMobBackfill.cs` ```csharp using System; using System.Collections; using UnityEngine; using GoogleMobileAds.Api; using GoogleMobileAds.Common; public class AdMobBackfill : MonoBehaviour { const string AdMobAdUnit = "YOUR_ADMOB_INTERSTITIAL_AD_UNIT"; readonly InterstitialBackfill nga = new InterstitialBackfill(); // InterstitialBackfill.cs, below InterstitialAd adMobAd; int adMobRetry; void Start() { LoadAdMob(); } // after MobileAds.Initialize void OnDestroy() { adMobAd?.Destroy(); } void LoadAdMob() { InterstitialAd.Load(AdMobAdUnit, new AdRequest(), (ad, error) => // Google Mobile Ads may call back off Unity's main thread. MobileAdsEventExecutor.ExecuteInUpdate(() => OnAdMobLoad(ad, error))); } void OnAdMobLoad(InterstitialAd ad, LoadAdError error) { if (this == null) return; if (ad != null && error == null) { adMobAd = ad; nga.OnMediationLoaded(); adMobRetry = 0; ad.OnAdFullScreenContentClosed += () => MobileAdsEventExecutor.ExecuteInUpdate(AfterAdMob); ad.OnAdFullScreenContentFailed += e => MobileAdsEventExecutor.ExecuteInUpdate(AfterAdMob); return; } nga.OnMediationLoadFailed(); adMobRetry++; StartCoroutine(RetryAdMob((float)Math.Pow(2, Math.Min(6, adMobRetry)))); } IEnumerator RetryAdMob(float seconds) { yield return new WaitForSecondsRealtime(seconds); if (this != null) LoadAdMob(); } // Call at the moment your game would show an interstitial. public void ShowInterstitial() { if (adMobAd != null && adMobAd.CanShowAd()) { PauseGame(); adMobAd.Show(); // the mediation always comes first } else if (!nga.TryShow(PauseGame, AfterNga)) ContinueGame(); // AdMob has no fill and NGA has nothing ready } void AfterAdMob() { adMobAd?.Destroy(); adMobAd = null; LoadAdMob(); ResumeGame(); ContinueGame(); } void AfterNga() { if (this == null) return; ResumeGame(); ContinueGame(); } // Your game's own code. void PauseGame() { } void ResumeGame() { } void ContinueGame() { } } ``` **Android (Kotlin)** · `AdMobBackfillActivity.kt` ```kotlin import android.app.Activity import android.os.Bundle import android.os.Handler import android.os.Looper import com.google.android.gms.ads.AdError import com.google.android.gms.ads.AdRequest import com.google.android.gms.ads.FullScreenContentCallback import com.google.android.gms.ads.LoadAdError import com.google.android.gms.ads.interstitial.InterstitialAd import com.google.android.gms.ads.interstitial.InterstitialAdLoadCallback import kotlin.math.min import kotlin.math.pow // Google Mobile Ads is initialized, as Google's documentation says, before this screen opens. class AdMobBackfillActivity : Activity() { private val handler = Handler(Looper.getMainLooper()) private val nga = InterstitialBackfill() // InterstitialBackfill.kt, below private var adMobAd: InterstitialAd? = null private var adMobRetry = 0 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) loadAdMob() } override fun onDestroy() { handler.removeCallbacksAndMessages(null) super.onDestroy() } private fun loadAdMob() { InterstitialAd.load( this, ADMOB_AD_UNIT, AdRequest.Builder().build(), object : InterstitialAdLoadCallback() { override fun onAdLoaded(ad: InterstitialAd) { adMobAd = ad nga.onMediationLoaded() adMobRetry = 0 ad.fullScreenContentCallback = object : FullScreenContentCallback() { override fun onAdDismissedFullScreenContent() = afterAdMob() override fun onAdFailedToShowFullScreenContent(adError: AdError) = afterAdMob() } } override fun onAdFailedToLoad(adError: LoadAdError) { if (isDestroyed) return adMobAd = null nga.onMediationLoadFailed() adMobRetry++ val delayMs = 1000L * 2.0.pow(min(6, adMobRetry)).toLong() handler.postDelayed({ loadAdMob() }, delayMs) } }, ) } // Call at the moment your game would show an interstitial. fun showInterstitial() { val adMob = adMobAd if (adMob != null) { pauseGame() adMob.show(this) // the mediation always comes first } else if (!nga.tryShow(this, ::pauseGame, ::afterNga)) { continueGame() // AdMob has no fill and NGA has nothing ready } } private fun afterAdMob() { adMobAd = null loadAdMob() resumeGame() continueGame() } private fun afterNga() { if (isDestroyed) return resumeGame() continueGame() } // Your game's own code. private fun pauseGame() {} private fun resumeGame() {} private fun continueGame() {} companion object { const val ADMOB_AD_UNIT = "YOUR_ADMOB_INTERSTITIAL_AD_UNIT" } } ``` **iOS (Swift)** · `AdMobBackfillViewController.swift` ```swift import UIKit import GoogleMobileAds // Google Mobile Ads is initialized, as Google's documentation says, before this screen opens. final class AdMobBackfillViewController: UIViewController, FullScreenContentDelegate { private static let adMobAdUnit = "YOUR_ADMOB_INTERSTITIAL_AD_UNIT" private let nga = InterstitialBackfill() // InterstitialBackfill.swift, below private var adMobAd: InterstitialAd? private var adMobRetry = 0.0 override func viewDidLoad() { super.viewDidLoad() loadAdMob() } private func loadAdMob() { Task { [weak self] in do { let ad = try await InterstitialAd.load(with: Self.adMobAdUnit, request: Request()) self?.adMobLoaded(ad) } catch { self?.adMobFailed() } } } private func adMobLoaded(_ ad: InterstitialAd) { adMobAd = ad nga.onMediationLoaded() adMobRetry = 0 ad.fullScreenContentDelegate = self } private func adMobFailed() { adMobAd = nil nga.onMediationLoadFailed() adMobRetry += 1 let delay = pow(2.0, min(6.0, adMobRetry)) DispatchQueue.main.asyncAfter(deadline: .now() + delay) { [weak self] in self?.loadAdMob() } } // Call at the moment your game would show an interstitial. func showInterstitial() { if let adMob = adMobAd { pauseGame() adMob.present(from: self) // the mediation always comes first } else if !nga.tryShow(from: self, pauseGame: pauseGame, afterAd: afterNga) { continueGame() // AdMob has no fill and NGA has nothing ready } } // FullScreenContentDelegate func adDidDismissFullScreenContent(_ ad: FullScreenPresentingAd) { afterAdMob() } func ad(_ ad: FullScreenPresentingAd, didFailToPresentFullScreenContentWithError error: Error) { afterAdMob() } func ad(_ ad: FullScreenPresentingAd, didRecordPaidEventWith value: AdValue) { AdMobRevenue.log(value, for: ad) // AdMob's revenue for NGA's reports: see Revenue and purchases } private func afterAdMob() { adMobAd = nil loadAdMob() resumeGame() continueGame() } private func afterNga() { resumeGame() continueGame() } // Your game's own code. private func pauseGame() {} private func resumeGame() {} private func continueGame() {} } ``` ### The helper `InterstitialBackfill` holds NGA's half for one screen: the load from the mediation's failure, the show when the mediation has nothing ready, and the resume when the show ends. The rewarded helper below has the same shape. **Unity (C#)** · `InterstitialBackfill.cs` ```csharp using System; using NGA; // NGA's interstitial backfill for one screen. Call OnMediationLoaded and OnMediationLoadFailed from your mediation's // interstitial load callbacks, and TryShow at the show moment when the mediation's ad is not ready. public sealed class InterstitialBackfill : NGAAdLoadCallback, NGAAdShowListener { const string NgaInterstitial = "plc_example_interstitial"; NGAAd backfill; bool mediationNoFill; // the mediation's latest load failed Action afterAd; public void OnMediationLoaded() { mediationNoFill = false; } public void OnMediationLoadFailed() { mediationNoFill = true; if (backfill == null || !backfill.IsReady()) NGASDK.LoadAd(NgaInterstitial, this); } // Shows NGA's ad if the mediation's latest load failed and NGA's ad is ready: pauseGame first, afterAd when the // show ends. Returns false, and calls nothing, when there is nothing to show. public bool TryShow(Action pauseGame, Action afterAd) { if (!mediationNoFill || backfill == null || !backfill.IsReady()) return false; pauseGame(); this.afterAd = afterAd; backfill.Show(this); // the mediation has no fill: NGA fills the moment return true; } // NGAAdLoadCallback public void OnLoaded(NGAAd ad) { backfill = ad; } public void OnFailed(string placementId, NGAError error) { } // the next mediation failure asks again public void OnExpired(NGAAd ad) { if (backfill != null && backfill.OpportunityId == ad.OpportunityId) backfill = null; } // NGAAdShowListener public void OnShowStarted(NGAAd ad) { } // the impression counted public void OnClicked(NGAAd ad) { } public void OnRewardResult(NGAAd ad, NGARewardResult result) { } // interstitial: never called public void OnCompleted(NGAAd ad, NGAShowCompletion completion) { } public void OnClosed(NGAAd ad) { backfill = null; Finish(); } public void OnShowFailed(NGAAd ad, NGAError error) { if (error.Code == NGAErrorCode.AlreadyShowing) return; // an NGA ad is still on screen; OnClosed follows if (!ad.IsReady()) backfill = null; Finish(); } void Finish() { var done = afterAd; afterAd = null; done?.Invoke(); } } ``` **Android (Kotlin)** · `InterstitialBackfill.kt` ```kotlin import android.app.Activity import network.nga.sdk.NGAAd import network.nga.sdk.NGAAdLoadCallback import network.nga.sdk.NGAAdShowListener import network.nga.sdk.NGAError import network.nga.sdk.NGAErrorCode import network.nga.sdk.NGASDK import network.nga.sdk.NGAShowCompletion // NGA's interstitial backfill for one screen. Call onMediationLoaded and onMediationLoadFailed from your mediation's // interstitial load callbacks, and tryShow at the show moment when the mediation's ad is not ready. class InterstitialBackfill : NGAAdLoadCallback, NGAAdShowListener { private var backfill: NGAAd? = null private var mediationNoFill = false // the mediation's latest load failed private var afterAd: (() -> Unit)? = null fun onMediationLoaded() { mediationNoFill = false } fun onMediationLoadFailed() { mediationNoFill = true if (backfill?.isReady() != true) NGASDK.loadAd(NGA_INTERSTITIAL, this) } // Shows NGA's ad if the mediation's latest load failed and NGA's ad is ready: pauseGame first, afterAd when the // show ends. Returns false, and calls nothing, when there is nothing to show. fun tryShow(activity: Activity, pauseGame: () -> Unit, afterAd: () -> Unit): Boolean { val ad = backfill?.takeIf { mediationNoFill && it.isReady() } ?: return false pauseGame() this.afterAd = afterAd ad.show(activity, this) // the mediation has no fill: NGA fills the moment return true } // NGAAdLoadCallback override fun onLoaded(ad: NGAAd) { backfill = ad } override fun onFailed(placementId: String, error: NGAError) {} // the next mediation failure asks again override fun onExpired(ad: NGAAd) { if (backfill === ad) backfill = null } // NGAAdShowListener override fun onShowStarted(ad: NGAAd) {} // the impression counted override fun onCompleted(ad: NGAAd, completion: NGAShowCompletion) {} override fun onClosed(ad: NGAAd) { if (backfill === ad) backfill = null finish() } override fun onShowFailed(ad: NGAAd, error: NGAError) { if (error.code == NGAErrorCode.ALREADY_SHOWING) return // an NGA ad is still on screen; onClosed follows if (backfill === ad && !ad.isReady()) backfill = null finish() } private fun finish() { val done = afterAd afterAd = null done?.invoke() } companion object { const val NGA_INTERSTITIAL = "plc_example_interstitial" } } ``` **iOS (Swift)** · `InterstitialBackfill.swift` ```swift import UIKit import NGASDK // NGA's interstitial backfill for one screen. Call onMediationLoaded and onMediationLoadFailed from your mediation's // interstitial load callbacks, and tryShow at the show moment when the mediation's ad is not ready. final class InterstitialBackfill: NSObject, NGAAdLoadCallback, NGAAdShowListener { private static let ngaInterstitial = "plc_example_interstitial" private var backfill: NGAAd? private var mediationNoFill = false // the mediation's latest load failed private var afterAd: (() -> Void)? func onMediationLoaded() { mediationNoFill = false } func onMediationLoadFailed() { mediationNoFill = true if backfill?.isReady != true { NGASDK.loadAd(Self.ngaInterstitial, callback: self) } } // Shows NGA's ad if the mediation's latest load failed and NGA's ad is ready: pauseGame first, afterAd when the // show ends. Returns false, and calls nothing, when there is nothing to show. func tryShow(from viewController: UIViewController, pauseGame: () -> Void, afterAd: @escaping () -> Void) -> Bool { guard mediationNoFill, let ad = backfill, ad.isReady else { return false } pauseGame() self.afterAd = afterAd ad.show(from: viewController, listener: self) // the mediation has no fill: NGA fills the moment return true } // NGAAdLoadCallback func onLoaded(_ ad: NGAAd) { backfill = ad } func onFailed(placementId: String, error: NGAError) {} // the next mediation failure asks again func onExpired(_ ad: NGAAd) { if backfill === ad { backfill = nil } } // NGAAdShowListener func onShowStarted(_ ad: NGAAd) {} // the impression counted func onCompleted(_ ad: NGAAd, completion: NGAShowCompletion) {} func onClosed(_ ad: NGAAd) { if backfill === ad { backfill = nil } finish() } func onShowFailed(_ ad: NGAAd, error: NGAError) { if error.code == .alreadyShowing { return } // an NGA ad is still on screen; onClosed follows if backfill === ad, !ad.isReady { backfill = nil } finish() } private func finish() { let done = afterAd afterAd = nil done?() } } ``` ## Rewarded Rewarded follows [the rule](#the-rule), with your mediation's rewarded ad in place of its interstitial. Only the reward is different: - **NGA decides only whether the reward was earned; what it is stays with your game.** Pay your own reward for that placement when `onRewardResult` says `granted`. - **The reward is earned on the device** as soon as the ad has been on screen long enough, even mid-ad. The ad then shows it as earned. - **A denial says why:** `SKIPPED` (the player closed the ad before earning it), `INTERRUPTED` (the ad stopped, for example the renderer crashed), or `REJECTED` (this ad grants no reward). Tell the player. - **Every rewarded show that counts an impression gets exactly one `onRewardResult`**, before `onCompleted` and `onClosed`. A show that ends before its impression gets none. - **Pay each `opportunityId` once.** It is unique to each ad. - **If the game is killed mid-ad**, `onAdClosedAfterRestart` on your `NGAListener` is called at the next launch with the result. When `rewardGranted` is true, call the example's pay-once method there: `RewardedBackfill.PayOnce` (C#), `RewardedBackfill.payOnce` (Kotlin), or `payOnce` on your `RewardedBackfill` instance (Swift). - **A reward that only makes sense in the moment** (a revive, a continue) needs a rule for that restart: pay it if the moment is still there, else convert or drop it. NGA reports only that it was earned. - **Keep the paid ids** where your game keeps its save data (`PlayerPrefs`, `SharedPreferences`, `UserDefaults` or your server), so a restart cannot pay twice. The examples keep them in memory for brevity. Wire `OnMediationLoaded` and `OnMediationLoadFailed` to your mediation's **rewarded** ad (*Rewarded ad to wire*, in [Your mediation](#your-mediation)) as the interstitial examples wire its interstitial. At the moment the player asks for a reward, show your mediation's rewarded ad if it is ready, and otherwise call `TryShow` / `tryShow`. **Unity (C#)** · `RewardedBackfill.cs` ```csharp using System.Collections.Generic; using UnityEngine; using NGA; // NGA's rewarded backfill. Call OnMediationLoaded and OnMediationLoadFailed from your mediation's // rewarded-ad load callbacks, as the interstitial examples above do. public class RewardedBackfill : MonoBehaviour, NGAAdLoadCallback, NGAAdShowListener { const string NgaRewarded = "plc_example_rewarded"; // Opportunity ids already paid. Keep them in your save data, so a restart cannot pay twice. static readonly HashSet paid = new HashSet(); NGAAd backfill; bool mediationNoFill; public void OnMediationLoaded() { mediationNoFill = false; } public void OnMediationLoadFailed() { mediationNoFill = true; if (backfill == null || !backfill.IsReady()) NGASDK.LoadAd(NgaRewarded, this); } // At the moment the player asks for a reward and your mediation's rewarded ad is not ready. public bool TryShow() { if (!mediationNoFill || backfill == null || !backfill.IsReady()) return false; PauseGame(); backfill.Show(this); return true; } // Also call this from NGAListener.OnAdClosedAfterRestart when rewardGranted is true. public static void PayOnce(string opportunityId) { if (!paid.Add(opportunityId)) return; // Give the player this placement's reward. } // NGAAdLoadCallback public void OnLoaded(NGAAd ad) { if (this != null) backfill = ad; } public void OnFailed(string placementId, NGAError error) { } public void OnExpired(NGAAd ad) { if (backfill != null && backfill.OpportunityId == ad.OpportunityId) backfill = null; } // NGAAdShowListener public void OnShowStarted(NGAAd ad) { } public void OnClicked(NGAAd ad) { } public void OnRewardResult(NGAAd ad, NGARewardResult result) { if (result.Granted) PayOnce(ad.OpportunityId); else Debug.Log($"No reward this time: {result.Denial}"); // Skipped, Rejected or Interrupted } public void OnCompleted(NGAAd ad, NGAShowCompletion completion) { } public void OnClosed(NGAAd ad) { backfill = null; ResumeGame(); } public void OnShowFailed(NGAAd ad, NGAError error) { if (error.Code == NGAErrorCode.AlreadyShowing) return; if (!ad.IsReady()) backfill = null; ResumeGame(); } // Your game's own code. void PauseGame() { } void ResumeGame() { } } ``` **Android (Kotlin)** · `RewardedBackfill.kt` ```kotlin import android.app.Activity import network.nga.sdk.NGAAd import network.nga.sdk.NGAAdLoadCallback import network.nga.sdk.NGAAdShowListener import network.nga.sdk.NGAError import network.nga.sdk.NGAErrorCode import network.nga.sdk.NGARewardResult import network.nga.sdk.NGASDK import network.nga.sdk.NGAShowCompletion // NGA's rewarded backfill, app-wide. Call onMediationLoaded and onMediationLoadFailed from your // mediation's rewarded-ad load callbacks, as the interstitial examples above do. object RewardedBackfill : NGAAdLoadCallback, NGAAdShowListener { private const val NGA_REWARDED = "plc_example_rewarded" // Opportunity ids already paid. Keep them in your save data, so a restart cannot pay twice. private val paid = mutableSetOf() private var backfill: NGAAd? = null private var mediationNoFill = false private var onDone: (() -> Unit)? = null fun onMediationLoaded() { mediationNoFill = false } fun onMediationLoadFailed() { mediationNoFill = true if (backfill?.isReady() != true) NGASDK.loadAd(NGA_REWARDED, this) } // At the moment the player asks for a reward and your mediation's rewarded ad is not ready. fun tryShow(activity: Activity, pauseGame: () -> Unit, resumeGame: () -> Unit): Boolean { val ad = backfill?.takeIf { mediationNoFill && it.isReady() } ?: return false pauseGame() onDone = resumeGame ad.show(activity, this) return true } // Also call this from NGAListener.onAdClosedAfterRestart when rewardGranted is true. fun payOnce(opportunityId: String) { if (!paid.add(opportunityId)) return // Give the player this placement's reward. } // NGAAdLoadCallback override fun onLoaded(ad: NGAAd) { backfill = ad } override fun onFailed(placementId: String, error: NGAError) {} override fun onExpired(ad: NGAAd) { if (backfill === ad) backfill = null } // NGAAdShowListener override fun onShowStarted(ad: NGAAd) {} override fun onRewardResult(ad: NGAAd, result: NGARewardResult) { if (result.granted) payOnce(ad.opportunityId) // else result.denial is SKIPPED, REJECTED or INTERRUPTED: tell the player } override fun onCompleted(ad: NGAAd, completion: NGAShowCompletion) {} override fun onClosed(ad: NGAAd) { if (backfill === ad) backfill = null finish() } override fun onShowFailed(ad: NGAAd, error: NGAError) { if (error.code == NGAErrorCode.ALREADY_SHOWING) return if (backfill === ad && !ad.isReady()) backfill = null finish() } private fun finish() { onDone?.invoke() onDone = null } } ``` **iOS (Swift)** · `RewardedBackfill.swift` ```swift import UIKit import NGASDK // NGA's rewarded backfill. Keep one instance for the app, for example on your game controller, and call // onMediationLoaded and onMediationLoadFailed from your mediation's rewarded-ad load callbacks, as the // interstitial examples above do. final class RewardedBackfill: NSObject, NGAAdLoadCallback, NGAAdShowListener { private static let ngaRewarded = "plc_example_rewarded" // Opportunity ids already paid. Keep them in your save data, so a restart cannot pay twice. private var paid = Set() private var backfill: NGAAd? private var mediationNoFill = false private var onDone: (() -> Void)? func onMediationLoaded() { mediationNoFill = false } func onMediationLoadFailed() { mediationNoFill = true if backfill?.isReady != true { NGASDK.loadAd(Self.ngaRewarded, callback: self) } } // At the moment the player asks for a reward and your mediation's rewarded ad is not ready. func tryShow(from viewController: UIViewController, pauseGame: () -> Void, resumeGame: @escaping () -> Void) -> Bool { guard mediationNoFill, let ad = backfill, ad.isReady else { return false } pauseGame() onDone = resumeGame ad.show(from: viewController, listener: self) return true } // Also call this from NGAListener.onAdClosedAfterRestart when rewardGranted is true. func payOnce(_ opportunityId: String) { guard paid.insert(opportunityId).inserted else { return } // Give the player this placement's reward. } // NGAAdLoadCallback func onLoaded(_ ad: NGAAd) { backfill = ad } func onFailed(placementId: String, error: NGAError) {} func onExpired(_ ad: NGAAd) { if backfill === ad { backfill = nil } } // NGAAdShowListener func onShowStarted(_ ad: NGAAd) {} func onRewardResult(_ ad: NGAAd, result: NGARewardResult) { if result.granted { payOnce(ad.opportunityId) } // else result.denial is .skipped, .rejected or .interrupted: tell the player } func onCompleted(_ ad: NGAAd, completion: NGAShowCompletion) {} func onClosed(_ ad: NGAAd) { if backfill === ad { backfill = nil } finish() } func onShowFailed(_ ad: NGAAd, error: NGAError) { if error.code == .alreadyShowing { return } if backfill === ad, !ad.isReady { backfill = nil } finish() } private func finish() { onDone?() onDone = nil } } ``` ## One ad per placement - **One ad per placement at a time.** Loading a placement that already has a ready ad gives you the same ad again; there is never a second ready ad for one placement. A game that needs two at once uses two placements. - **One NGA placement can back two of your mediation's ad units** (two rewarded ad units, say). They share its one live ad, its caps and its row in the report. For separate caps or reporting, create one placement each. - **One full-screen ad at a time, app-wide.** A `show` while another NGA full-screen ad is on screen fails with `ALREADY_SHOWING`, and the ad stays ready. - **A refused show keeps the ad ready** for your next moment: `ACTIVITY_NOT_RESUMED` (the screen is not in front) and, on Android, `RENDER_NOT_AVAILABLE / webview.unavailable`. See [After `onShowFailed`](https://nga.io/docs/sdk/reference/callbacks/#ngaadshowlistener). - **A loaded ad can be shown for 30 minutes.** Then it expires, and the next mediation failure loads a new one. See [`NGAAd`](https://nga.io/docs/sdk/reference/values/#ngaad). The ad keeps running when the screen that called `show` is rotated or recreated: it runs in NGA's own screen. Its callbacks still go to the listener you passed to `show`, and a new screen can read the ad's `state`. ## Next Read how [attribution](https://nga.io/docs/sdk/attribution/) works, then [test your integration](https://nga.io/docs/sdk/testing/). # Attribution How NGA knows a promotion brought an install, why both games carry the SDK, and how your own MMP sees those installs too. *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/attribution/* ## Both games carry the SDK Put the SDK in the game that shows the ad and in every game it promotes. The core library alone is enough in a game that shows no NGA ads. Nothing else is needed: the two SDKs and NGA's server do the measuring. - **A tap opens the store directly**, with NGA's own click id. - **The promoted game reports its install** when it first starts, and NGA's server joins it to the tap. On Android the join is the click id, which Google Play hands to the promoted game's SDK; on iOS it is the IDFV (vendor id) the two games share. - **An install counts** when the promoted game first starts within 7 days of the tap. If the player tapped more than once, the last tap wins. Two limits: - **On iOS, both games must be in one Apple developer account.** The IDFV is shared only by one account's apps on a device. For a pair in different accounts NGA matches no iOS installs, and the report marks the pair *iOS installs not matchable* rather than showing 0. Android is unaffected. - **Only players with analytics consent, and not under child treatment,** have their installs matched. NGA's install numbers are a floor. ## When a game is promoted A game is promoted to players on a platform only after a store-installed release build has run with the SDK there. NGA cannot see installs of a game without the SDK, so such a game is never promoted. A sideloaded build, a TestFlight build or a test device's build does not count. On Google Play, a build from a testing track (internal, closed or open) counts only once its version is at or below the one your public store listing serves, as NGA last read it: a testing track ahead of production keeps the game *Pending*. The portal shows the state per platform, on the game's *Promotion*: | *State* | Means | | --- | --- | | *Waiting for the SDK* | no store build of the game has started with the SDK yet | | *Pending* | a store build has started with the SDK. On iOS, the game is promoted from its first live events. On Google Play, from the first live events of a release build installed from the store at or below the version its public listing serves | | *Promotable* | your other games can show it while its *Promoted* switch is on | You set nothing: the state follows your store builds. A host game promotes only games whose *Promoted* switch is on and that are *Promotable* on its platform. Your registered test devices do not wait; see [Test mode](https://nga.io/docs/sdk/testing/#test-mode). **A game that stays *Pending* on Google Play** while you test on a testing track is waiting for a production release that carries the SDK. Release a build with the SDK to production; NGA reads a pending game's listing again about once a day, so its state follows within about a day of the listing showing that version. ## Your MMP By default, your MMP (AppsFlyer, Adjust) counts installs from NGA as organic, because the tap opens the store directly. To see them as NGA's, give NGA your MMP's click and impression URLs for each promoted game and platform. NGA's server, not the SDK, calls the impression URL once per impression and the click URL once per tap. > **In the portal (portal.nga.io).** > The promoted game's *Promotion* > *Your MMP (optional)*, per platform: *MMP click URL* and *MMP impression URL*, then *Save the URLs*. Both are optional and `https`; the portal checks them when you save. In your MMP, create the two URLs for the promoted game, as for any ad network that reports server-to-server. Put NGA's macros where your MMP takes each value: | Macro | NGA fills in | | --- | --- | | `{click_id}` | NGA's id for the tap, the same for a click and its impression | | `{opportunity_id}` | NGA's id for the ad, the `opportunityId` your game sees | | `{host}` | the store id of the game that showed the ad | | `{platform}` | `android` or `ios` | | `{timestamp}` | when the impression or tap happened, in milliseconds since 1970 | | `{gaid}`, `{idfa}`, `{ip}` | the player's advertising id and IP address, only where consent allows (below) | | | AppsFlyer | Adjust | | --- | --- | --- | | Hosts the portal accepts | `appsflyer.com`, `onelink.me` | `adjust.com`, `adjust.io` | | URL form | `pid` is your media source for this traffic (AppsFlyer's own cross-promotion source is `af_cross_promotion`). The click URL ends in `redirect=false`, AppsFlyer's mark of a click sent from a server | the server-to-server form: host `s2s.adjust.com`, the token of a link you created for NGA's traffic, and `s2s=1` | | `{click_id}` | `clickid`, as in the example | Adjust has no click id parameter: pass it as a parameter of your choice, which Adjust's callbacks can read back | | `{gaid}` (Android) | `advertising_id` | `gps_adid` | | `{idfa}` (iOS, in place of `{gaid}`) | `idfa` | `idfa` | | `{ip}` | `af_ip` | `ip_address`, IPv4 only | | iOS app id | the App Store id with `id` before it (`id1234567890`) | — | | Limits | AppsFlyer keeps 24 characters of `af_siteid`; for longer store ids, put `{host}` in `af_sub_siteid` instead | Adjust refuses a server-to-server click without an advertising id | | Full parameter list | [link parameters](https://support.appsflyer.com/hc/en-us/articles/207447163-About-link-structure-and-parameters), [cross-promotion attribution](https://support.appsflyer.com/hc/en-us/articles/4410480466065-Cross-promotion-attribution-for-developers) | [server-to-server setup](https://help.adjust.com/en/article/set-up-server-to-server-s2s-measurement) | The portal checks that `{gaid}`, `{idfa}` and `{ip}` sit in the parameters above. The parameters beyond NGA's macros are your MMP's. `AppsFlyer, Android` ```text https://app.appsflyer.com/com.example.puzzle?pid=af_cross_promotion&c=nga&af_siteid={host}&clickid={click_id}&advertising_id={gaid}&af_ip={ip}&redirect=false https://impression.appsflyer.com/com.example.puzzle?pid=af_cross_promotion&c=nga&af_siteid={host}&clickid={click_id}&advertising_id={gaid}&af_ip={ip} ``` `Adjust, Android` ```text https://s2s.adjust.com/abc123?s2s=1&campaign=nga&adgroup={host}&gps_adid={gaid}&ip_address={ip}&nga_click_id={click_id} https://s2s.adjust.com/impression/abc123?s2s=1&campaign=nga&adgroup={host}&gps_adid={gaid}&ip_address={ip}&nga_click_id={click_id} ``` **What NGA sends, and when:** | Player | NGA calls your MMP | `{gaid}`, `{idfa}`, `{ip}` | | --- | --- | --- | | Under child treatment | no | — | | Ads personalization `DENIED`, or `UNKNOWN` where the law requires consent, when the event was recorded or when it was sent; or opted out of sale or sharing in the US | yes | empty. AppsFlyer counts the impression or click but cannot attribute it to a device; Adjust refuses it | | Everyone else: ads personalization `GRANTED`, or `UNKNOWN` where no consent is required ([Consent](https://nga.io/docs/sdk/privacy/#consent)) | yes | filled; `{idfa}` only for players who allowed tracking | - **Test traffic never reaches your MMP**: test builds, registered test devices and debug builds. - **Delivery.** Each impression and each tap is sent at least once. A call that fails is retried for up to 24 hours, so in rare cases your MMP may count one twice. The report shows each URL's sent and failed counts. **In your MMP** you see NGA's media source: its impressions, its clicks, and the installs your MMP attributes to them by its own rules. **NGA's report is the attribution of record.** The two can differ, for example when your MMP cannot attribute a call that has no device id. ## What you see in the report The portal's *Report*, per host game, per promoted game, per placement, per format and per day (UTC): - requests and fills; - impressions, clicks and click-through rate; - matched installs, and installs per thousand impressions; - installs without a click (Android): installs of a promoted game that NGA saw but could match to no tap within the window, a first start more than 7 days after the tap, say; the report lists them under no host game; - day-1 and day-7 retention of matched installs; - the share of impressions drawn in the host game's own style, rather than in NGA's standard banner with its colors; - your MMP calls, sent and failed, per URL. An event that arrives late, from a device that was offline, is counted on the day it happened, so the most recent days still change; the report marks them *still updating*. Everything from test devices and test builds is in the report's test view, never in the report itself. # Test your integration Register your test device in the portal, read the log, and run through the checklist for each format. A game not on a store yet can be tested too. *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/testing/* ## Before you start Testing needs your real app key and placement ids from the portal, and a network connection for the first launch. See [Set up in the portal](https://nga.io/docs/sdk/portal/). ## Test mode Test mode is on if either is true: - **The builder flag**, `testMode(true)`, which the [Initialize](https://nga.io/docs/sdk/initialize/) snippets set in debug builds. - **A registered test device.** Register a phone once in the portal, and every build of every one of your games on it runs in test mode, release builds included. In test mode: - NGA serves your own games, with the same caps as live traffic. - Nothing is paid. - The install's events go to the report's *test view* only, not to your main report or your MMP. **A registered test device sees more than a player does**, among your games whose *Promoted* switch is on: - your other games, as soon as any build of them (debug included) has run once with the SDK on that platform, even before they are promotable to players; - your games that are already installed on it, which a player's device is not shown; - your games that are [not on a store yet](https://nga.io/docs/sdk/portal/#a-game-not-on-a-store-yet), which only registered test devices are shown. ## Register a test device 1. Set the log level to `DEBUG` before `initialize`, as the [Initialize](https://nga.io/docs/sdk/initialize/) snippets do in debug builds. A release build shows the id too, once you call `setLogLevel(DEBUG)` there. 2. Launch the game and find the test-device id in the log, in one of these lines: ```text test-device id (App Set ID): — it covers all your games on this device; add it in the portal to put this device in test mode test-device id (App Set ID): — it covers this game only (this build was not installed by Google Play); add it in the portal to put this device in test mode test-device id (IDFV): — it covers all your games on this device; add it in the portal to put this device in test mode ``` The line says what the id covers: - **Android, a build installed by Google Play** (a testing track or the store): one id for all your games on that device. Register it once. - **Android, a build installed any other way** (Android Studio, `adb`, Firebase App Distribution, a device farm): an id of its own in each game. Register each game's id, on the same device in the portal. Every build you sideload while integrating is this kind, so expect one id per game until your games come from Play. - **iOS**: the IDFV, one id for all your games on that device under one Apple developer account. Register it once. 3. Register it in the portal, under *Test devices*. > **In the portal (portal.nga.io).** > *Test devices* > *Add a device*: a *Name (optional)* and the *Test-device id*, then *Add the device*. A game started in test mode from an id that is not registered yet also appears there, under *Recent test installs not yet registered*, with *Add to device…*, which puts the id on a device you name or one you already have. A device's page lists its ids with what each covers. Remove an id there when you are done. The device enters test mode at the first launch whose init carries its id: | Build | Test mode starts | The id is read | | --- | --- | --- | | Android, release | at the second launch of a fresh install (the first init carries no id) | only if analytics consent is not denied and the player is not under child treatment | | Android, debuggable with `testMode(true)` | at the first launch | always, whatever the consent | | iOS | at the launch after its first events have been sent | under the same rule as an Android release build | If the id is not read (for example, consent denied), only the builder flag applies. The device's page in the portal shows each of your games it ran with the SDK, the consent and configuration in force, its recent ad requests with the reason for each no-fill, and its ad errors. ## The log | Engine | Where to read it | | --- | --- | | Android | Logcat, tag `NGASDK` | | iOS | the Xcode console or Console.app, subsystem `network.nga.sdk`, category `NGASDK` | | Unity | Logcat (Android) or the Xcode console (iOS). The Unity console shows only the C# `[NGA]` lines and your callbacks' own logs | `Terminal` ```shell adb logcat -s NGASDK ``` At `DEBUG`, init logs the test-device id (above) and one summary when it completes: `The DEBUG init summary` ```text init summary test mode: on (the builder's testMode flag) render module: found, nga-sdk-render , started app key: well-formed, accepted by the server placements in the configuration: plc_example_native (native), plc_example_interstitial (interstitial) consent: analytics granted, ads_personalization granted, age unknown, child treatment false; source … server numbers: … ``` - **test mode:** `off`, `on (the builder's testMode flag)`, `on (this device is registered as a test device in the portal)`, or `on (the builder's testMode flag and a registered test device)`. - **render module:** should say `found … started`. Otherwise it says why ad calls fail with `RENDER_NOT_AVAILABLE`: `not found` (the render library is not in the build), or a version that does not match `nga-sdk`. - **app key:** accepted by the server. A launch that started from the saved configuration says so. - **placements in the configuration:** every placement of this game, with its format. A `loadAd` made before init gets a line of its own saying whether its placement is one of them. - **consent:** the consent in effect, the age and whether child treatment applies, and where each came from: your calls, the TCF or GPP keys, or nothing set yet. - **server numbers:** the configuration in force. **An offline first launch prints no summary.** With no network and no saved configuration, init fails with `NETWORK / init.unreachable`, one warning per attempt, and the SDK retries in the background at growing intervals; loads wait for init. The summary comes with the first launch that reaches NGA, and the checklist's airplane-mode check assumes one. **`nga-sdk-render is not in this build`** (iOS: `NGASDKRender`), one `WARN` at `initialize`: the render library is missing, and every ad call answers `RENDER_NOT_AVAILABLE / render.absent`. It never appears when the library is in the build. **`purchase capture off … missing=[permission:com.android.vending.BILLING]`** at start, on an Android emulator image without the Play Store: the permission Play Billing declares is never granted there, so the SDK sees no purchases on that image. A phone with Play grants it. Nothing to fix. Outside test mode the log never prints a player's identifiers; the test-device id is the one exception, so that you can register a release build. **After init, at `DEBUG`, one line per ad event**, with the placement and its format and never an identifier: `The DEBUG ad lines` ```text loadAd plc_example_native (native): served, promoting "Puzzle Example" loadAd plc_example_rewarded (rewarded): joins the load in flight; answered with it loadAd plc_example_rewarded (rewarded): served, promoting com.example.puzzle (2 loadAd calls) loadAd plc_example_interstitial (interstitial): NO_FILL / no_fill.decision show plc_example_native (native): refused ACTIVITY_NOT_RESUMED / show.activity.not_resumed show plc_example_native (native): started show plc_example_native (native): ended, ended_by close ``` - **`loadAd … : served, promoting …`**, with the promoted game's name (the banner) or its package name or bundle id (a full-screen ad), or the error's code and detail, for every load's answer, the loads that waited for init included. A load that answered several `loadAd` calls says how many. - **`loadAd … : joins the load in flight`** for a `loadAd` answered by a load already running, and **`waits for the next attempt in … ms, after …`** for one made while the SDK waits to retry a failed load, so a load you gave up on still leaves a line. - **`show … : refused`** with the code and detail, for every `show` that fails. - **`show … : started`** when the banner has landed or the full-screen ad is on screen (before `onShowStarted`, which is the impression), and **`ended, ended_by …`** when the show ends, with what ended it: `close`, `view_gone`, `window_too_small`, `destroyed`, `process_death`, `child_treatment`, `stopped` (NGA stopped the SDK) or `render_failed`. Log `error.code` and `error.detail` in `onFailed` and `onShowFailed`, and look them up on [Errors](https://nga.io/docs/sdk/reference/errors/). ## "No fill" while testing `NO_FILL` is a normal answer, and the bottom of the screen stays empty. While testing, it usually means one of these: - **You have only one game with the SDK.** A game never promotes itself: a test device needs a second of your games, registered with *Promoted* on (it is on from registration) and run once with the SDK on that platform, any build. The device then asks again within the hour. The test device's page in the portal names this reason. - **For the native banner: NGA has not finished reading your game's listing** ([What the banner shows](https://nga.io/docs/sdk/native-cross-promo/#what-the-banner-shows)). - **For full-screen ads: none of your other games with *Promoted* on has a video** in the portal. - **A cap is reached** (`no_fill.cap`), or **the server asked the device to wait**; `error.retryAfterMillis` says how long. - **The game's *Shows cross-promo* or *Serving* is off**, or the placement's serving is stopped, in the portal. ## Testing your own code A game's own tests reach NGA's part through your own types, not the SDK's: - **Values you can make in a test:** `NGAError`, `NGAResult`, `NGAInitResult`, `NGARewardResult` and `NGAImpression` have public constructors on Android and in C#; on iOS, `NGAError`, `NGARewardResult` and `NGAImpression` have public initializers. - **`NGAAd` is the SDK's handle.** On Android it is an interface and on iOS a protocol, which a test double can implement; in C# it is a sealed class with an internal constructor, so a C# test cannot make one. - So keep the rules your callbacks apply (when to show, what a reward pays, when the banner closes) in your own small interface or class, call the SDK from behind it, and test that. The guide's examples are shaped that way: `InterstitialBackfill` and `RewardedBackfill` hold the rule, and the screens and mediation classes call them. The SDK runs only on a device, an emulator or a simulator: in the Unity Editor `initialize` reports `INVALID_CONFIG / platform.unsupported` and nothing else happens or throws. ## Checklist **Initialize** - `onInitialized` reports `success`, on a device with a network. - Started again in airplane mode, it reports `success` with `fromCache` true. - The `DEBUG` init summary shows the render library found (if your game shows NGA ads), your app key accepted, and your placements in the configuration. **Native cross-promo** - The banner slides up at the bottom of the screen, centered, over nothing of your own. - `onShowStarted` is called about a second after the banner lands. - A tap on the banner opens the store for the promoted game, and `onClicked` is called. For a game not on a store yet, or one already installed on this device, nothing opens; only a test device is shown those. - Closing the banner (its close button, your `close()`, or leaving the screen) calls `onCompleted` then `onClosed` after the impression counted, or `onClosed` alone before it. - Your game calls `close()` before it shows anything of its own at the bottom of the screen, and, in Unity, when it leaves that screen. - If your game shows a banner ad on that screen, it disappears before NGA's banner lands and comes back, refreshing, when NGA's banner closes; and no `NGACrossPromo: no banner yield registered` warning is in the log. - On a tablet, the banner is the tablet size; rotated, it moves to the new bottom center. **Full-screen backfill** - With your mediation filling, NGA's ad never shows and NGA's placement is never loaded. - With your mediation failing, NGA's ad loads and shows at the next ad break. To force a failure in a debug build, change one character of the mediation's ad unit id. - The game pauses before the ad and resumes on `onClosed`. - The close button appears, and back works on Android once it does. **Rewarded** - Watching long enough calls `onRewardResult` with `granted`, once, and your game pays its reward. - Closing early gives `granted` false with `SKIPPED`, and your game says so. - Killing the game mid-ad and relaunching calls `onAdClosedAfterRestart` once, and a reward already paid is not paid again. **Privacy** - Your consent screen's answer reaches `setConsent`, and `getConsent()` returns it. - A *Mixed* game's age gate reaches `setAge`. - Your Data safety and App Privacy answers include the SDK's part; see [Store privacy forms](https://nga.io/docs/sdk/privacy/#store-privacy-forms). **In the portal** - Your test device's page shows your game's launches and its ad requests. - The report's test view shows the impressions and clicks you made. Then [go live](https://nga.io/docs/sdk/go-live/). # Go live The release checklist, how to stop serving, what changes without an app release, and SDK versions. *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/go-live/* ## Release checklist **In your game:** - **Test mode off in the release build.** `testMode` follows your debug flag (as in the [Initialize](https://nga.io/docs/sdk/initialize/) snippets) and is not hard-coded `true`. - **Consent wired.** The builder gets the player's stored answer, and your consent screen calls `setConsent`. See [Consent](https://nga.io/docs/sdk/privacy/#consent). - **Age wired, for a game whose audience is *Mixed*.** Your age gate calls `setAge`. See [Age and audience](https://nga.io/docs/sdk/privacy/#age-and-audience). - **The banner's rule kept,** and the [banner yield](https://nga.io/docs/sdk/native-cross-promo/#your-own-banner-ad) registered if your game shows a banner ad. See [Where the banner may show](https://nga.io/docs/sdk/native-cross-promo/#where-the-banner-may-show). - **The backfill rule kept.** See [The rule](https://nga.io/docs/sdk/backfill/#the-rule). - **Rewards keyed by `opportunityId`,** and paid from `onAdClosedAfterRestart` too. See [Rewarded](https://nga.io/docs/sdk/backfill/#rewarded). - **Store forms updated** with the SDK's part. See [Store privacy forms](https://nga.io/docs/sdk/privacy/#store-privacy-forms). - **A release build tested** on a [registered test device](https://nga.io/docs/sdk/testing/#register-a-test-device), with the package name or bundle id registered for the game. - **Hosts allowed** if your game or its players' networks filter traffic. See [Hosts the SDK contacts](https://nga.io/docs/sdk/privacy/#hosts-the-sdk-contacts). **In the portal, for each game:** - **Store link added.** For a game registered before launch, paste the store link once it is listed; the app key does not change. Until then the game shows only on your test devices. See [A game not on a store yet](https://nga.io/docs/sdk/portal/#a-game-not-on-a-store-yet). - **Its two cross-promo switches** in its *Overview* (both on by default): *Shows cross-promo* on if it should show your other games, *Promoted* on if your other games should show it; and *Serving* not stopped for the game or its placements. - ***Audience* set** on its *Promotion* for each platform, as you answered each store. - **Its copy approved** under *Creatives* > *Native cross-promo*, a *Short name* given if its store title is longer than 20 characters, and its motif picked or left to *Automatic*. - **Its video under *Creatives* > *Full-screen***, if it should appear in your other games' full-screen backfill. - **Its MMP URLs under *Promotion***, if you want your MMP to see the installs NGA brings. See [Your MMP](https://nga.io/docs/sdk/attribution/#your-mmp). - **Its placements' caps** as you want them. See [Caps](https://nga.io/docs/sdk/portal/#caps). **Then release** a store build of each game with the SDK. A game is promoted to players on a platform only after a store-installed release build has run with the SDK there (on Google Play, a production release: a testing track's build ahead of it does not count); its *Promotion* > *State* goes from *Waiting for the SDK* to *Pending* to *Promotable*. See [When a game is promoted](https://nga.io/docs/sdk/attribution/#when-a-game-is-promoted). ## Stop serving To stop a game, turn off *Serving* on its *Overview*. To stop one placement, use *Stop serving* on it. Turn either back on in the same place. After a stop: - requests get no fill, and games already installed check again within an hour; - an ad already loaded can still start showing until it expires (30 minutes at most); - a banner already on screen stays until its show ends. A game's two cross-promo switches take it out of cross-promo one way each. With *Shows cross-promo* off, it no longer shows your other games: its requests get no fill, and installs ask again within an hour. With *Promoted* off, your other games no longer show it. Turn both off to take it out both ways. NGA does not notice when a game leaves a store, so turn *Promoted* off for a game you take off one. ## When NGA turns a game off NGA can turn a game off at one of two levels, for example when it misbehaves. Neither shows in the portal, and your own switches cannot undo it; ask NGA at [hi@nga.network](mailto:hi@nga.network). - **Ads off.** The game gets no NGA ad: every load fails with `NO_FILL / no_fill.decision`, and no other game promotes it. Its SDK keeps collecting and sending as before. - **SDK off**, on one platform: NGA switches the app key off there, and the other platform is untouched. From its next request, the SDK stops collecting; `initialize` and every load fail with `DISABLED / app_key.disabled`, and `onError` is called. Every loaded ad expires at once (`onExpired`), a banner on screen closes (`onClosed`), and a full-screen ad already on screen plays to its end. When NGA turns it back on, loads are served again once their `retryAfterMillis` has passed (an hour after *Ads off*), and an SDK that was off resumes at its next launch or return to the foreground, without a new build. When it resumes on a return to the foreground, a placement with *Prefetch* loads at the game's next `loadAd`, not before. ## Without an app release The SDK takes its configuration from NGA at every launch. These change without a release: - which of your games are promoted, and which game fills each placement; - placements' caps, prefetch and auto-reload, and serving; - the audience and the MMP URLs; - the banner's lines and short names, and your full-screen videos; - how the ads look and behave, within the SDK's own limits. These need a release: an SDK update, a new placement id in your code, and anything in your own integration, such as your consent wiring or where the banner shows. A placement created after your release reaches the game at its next launch. A `loadAd` for a placement your game does not know yet waits for the fresh configuration before it fails. ## SDK versions These pages install 0.1.0. The [changelog](https://nga.io/docs/sdk/changelog/) lists each new version, with the support terms; to update, change one version number ([Updating](https://nga.io/docs/sdk/install/#updating)). A version that NGA has to stop urgently fails with `DISABLED / sdk.retired` through `onError`, which tells you to update; its loaded ads expire, as with *SDK off* above. # Revenue and purchases Optional. Most of this needs no code. Add the calls below for ad revenue from networks the SDK cannot see, StoreKit 2 purchases, your own user id, and NGA's own impressions. *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/revenue/* ## Ad revenue from your mediation **MAX and LevelPlay: nothing to do.** When your game ships AppLovin MAX or Unity LevelPlay, the SDK records the revenue of each of their impressions from `initialize` on, even one that happens during a slow first launch. This covers the mediation your game runs on. A MAX or LevelPlay SDK that is in your build only as another mediation's adapter (AppLovin's or ironSource's inside AdMob, say) serves no impressions of its own and the SDK hears nothing from it; that revenue arrives through the mediation that served the ad. **AdMob and every other network: `logAdRevenue`.** AdMob reports revenue only to each ad object, so the SDK cannot see it. Pass every paid event to `logAdRevenue`, impressions served by AdMob's AppLovin, ironSource or other adapters included: the SDK's MAX and LevelPlay hooks do not see AdMob's impressions, so nothing is counted twice: **Unity (C#)** · `AdMobRevenue.cs` ```csharp using GoogleMobileAds.Api; using NGA; public static class AdMobRevenue { // Call once for each AdMob ad you load: AdMobRevenue.Track(interstitialAd, NGAAdFormat.Interstitial) public static void Track(InterstitialAd ad, NGAAdFormat format) { ad.OnAdPaid += value => Log(value, ad.GetAdUnitID(), ad.GetResponseInfo(), format); } public static void Track(RewardedAd ad, NGAAdFormat format) { ad.OnAdPaid += value => Log(value, ad.GetAdUnitID(), ad.GetResponseInfo(), format); } static void Log(AdValue value, string adUnitId, ResponseInfo info, NGAAdFormat format) { var revenue = new NGAAdRevenue.Builder(NGAAdRevenueMediation.AdMob, value.Value, value.CurrencyCode, Precision(value.Precision)) .AdUnitId(adUnitId) .AdFormat(format); var source = info?.GetLoadedAdapterResponseInfo()?.AdSourceName; if (source != null) revenue.Network(source); NGASDK.LogAdRevenue(revenue.Build()); // AdValue.Value is already in micros } static NGARevenuePrecision Precision(AdValue.PrecisionType precision) { switch (precision) { case AdValue.PrecisionType.Precise: return NGARevenuePrecision.Exact; case AdValue.PrecisionType.Estimated: return NGARevenuePrecision.Estimated; case AdValue.PrecisionType.PublisherProvided: return NGARevenuePrecision.PublisherDefined; default: return NGARevenuePrecision.Undefined; } } } ``` **Android (Kotlin)** · `AdMobRevenue.kt` ```kotlin import com.google.android.gms.ads.AdValue import com.google.android.gms.ads.interstitial.InterstitialAd import network.nga.sdk.NGAAdFormat import network.nga.sdk.NGAAdRevenue import network.nga.sdk.NGAAdRevenueMediation import network.nga.sdk.NGARevenuePrecision import network.nga.sdk.NGASDK object AdMobRevenue { // Call once for each AdMob interstitial you load; rewarded and other formats work the same way. fun track(ad: InterstitialAd) { ad.setOnPaidEventListener { value -> val revenue = NGAAdRevenue.Builder( NGAAdRevenueMediation.ADMOB, value.valueMicros, // already in micros value.currencyCode, precision(value.precisionType), ) .adUnitId(ad.adUnitId) .adFormat(NGAAdFormat.INTERSTITIAL) ad.responseInfo.loadedAdapterResponseInfo?.adSourceName?.let { revenue.network(it) } NGASDK.logAdRevenue(revenue.build()) } } private fun precision(type: Int): NGARevenuePrecision = when (type) { AdValue.PrecisionType.PRECISE -> NGARevenuePrecision.EXACT AdValue.PrecisionType.ESTIMATED -> NGARevenuePrecision.ESTIMATED AdValue.PrecisionType.PUBLISHER_PROVIDED -> NGARevenuePrecision.PUBLISHER_DEFINED else -> NGARevenuePrecision.UNDEFINED } } ``` **iOS (Swift)** · `AdMobRevenue.swift` ```swift import Foundation import GoogleMobileAds import NGASDK enum AdMobRevenue { // Call from the ad's FullScreenContentDelegate, which Google Mobile Ads 13.12 calls for each paid event: // func ad(_ ad: FullScreenPresentingAd, didRecordPaidEventWith value: AdValue) { AdMobRevenue.log(value, for: ad) } static func log(_ value: AdValue, for ad: FullScreenPresentingAd) { // AdMob's iOS value is in currency units: convert once, by rounding, to micros. let micros = value.value.multiplying(byPowerOf10: 6) .rounding(accordingToBehavior: NSDecimalNumberHandler(roundingMode: .plain, scale: 0, raiseOnExactness: false, raiseOnOverflow: false, raiseOnUnderflow: false, raiseOnDivideByZero: false)) .int64Value let revenue = NGAAdRevenue.Builder(mediation: .admob, revenueMicros: micros, currency: value.currencyCode, precision: precision(value.precision)) if let ad = ad as? InterstitialAd { revenue.adFormat(.interstitial).adUnitId(ad.adUnitID) if let source = ad.responseInfo.loadedAdNetworkResponseInfo?.adSourceName { revenue.network(source) } } else if let ad = ad as? RewardedAd { revenue.adFormat(.rewarded).adUnitId(ad.adUnitID) if let source = ad.responseInfo.loadedAdNetworkResponseInfo?.adSourceName { revenue.network(source) } } NGASDK.logAdRevenue(revenue.build()) } private static func precision(_ precision: AdValuePrecision) -> NGARevenuePrecision { switch precision { case .precise: return .exact case .estimated: return .estimated case .publisherProvided: return .publisherDefined default: return .undefined } } } ``` `mediation` is the layer that served the ad: `ADMOB`, `MAX`, `LEVELPLAY` or `OTHER`. An app with one network and no mediation uses `NONE` and sets `network`. Every field, with its rules and the errors a bad value gets, is on [`NGAAdRevenue`](https://nga.io/docs/sdk/reference/configuration/#ngaadrevenue). `logAdRevenue` returns an [`NGAResult`](https://nga.io/docs/sdk/reference/values/#ngaresult) immediately. Logging an ad the SDK already records (a MAX or LevelPlay impression) does no harm as long as the call carries that mediation's own impression id (MAX's ad id, LevelPlay's auction id) or none: NGA keeps one copy. With an id of your own, both copies are kept. ## Purchases **Most games need no code:** Google Play Billing 8 or later, StoreKit 1, and Unity IAP 4. From `initialize` on, the SDK sees these purchases without changing your purchase flow. It never acknowledges, consumes or finishes a purchase. A StoreKit 1 restore is not recorded as a new purchase, with one exception: after a reinstall, a restored subscription's latest period can be recorded once if the SDK had not seen it before; NGA counts each transaction once across installs. **iOS games on StoreKit 2: one call per purchase.** A StoreKit 2 consumable that you finish immediately reaches only your own code, so pass every successful `Product.purchase()` result to `logPurchase`. A purchase the SDK also sees on its own is still recorded once. **iOS (Swift)** · `Store.swift` ```swift import StoreKit import NGASDK enum Store { static func buy(_ product: Product) async throws { let result = try await product.purchase() guard case .success(let verification) = result else { return } NGASDK.logPurchase(verification) // every successful purchase, consumable or not if case .verified(let transaction) = verification { // Deliver the item, then: await transaction.finish() } } } ``` **Unity IAP 5: one call per purchase.** On iOS, Unity IAP 5 uses StoreKit 2. Pass the order's JWS to `LogPurchase` just before `ConfirmPurchase`. On Android the call records nothing and returns `accepted`, so the same script works on both platforms. **Unity (C#)** · `Purchases.cs` ```csharp using NGA; using UnityEngine.Purchasing; public class Purchases { readonly StoreController store = UnityIAPServices.StoreController(); public Purchases() { store.OnPurchasePending += OnPurchasePending; } void OnPurchasePending(PendingOrder order) { // Deliver the item, then: NGASDK.LogPurchase(order.Info.Apple?.jwsRepresentation); // iOS: the StoreKit 2 transaction; Android: ignored store.ConfirmPurchase(order); } } ``` What the SDK does not see: other stores (Amazon, Samsung, Huawei, web shops), Play Billing below version 8, purchases granted only on your server, and purchases made before the SDK first ran. Google Play refunds are not visible on the device. ## Your own user id `setCustomerUserId` attaches your own id for the player, such as your account id, so NGA's data can be joined with yours. NGA stores it hashed. **Unity (C#)** ```csharp using NGA; using UnityEngine; public static class PlayerAccount { public static void OnSignedIn(string accountId) { var result = NGASDK.SetCustomerUserId(accountId); if (!result.Accepted) Debug.LogWarning($"NGA customer user id: {result.Error.Detail}"); } public static void OnSignedOut() { NGASDK.SetCustomerUserId(null); } } ``` **Android (Kotlin)** ```kotlin import android.util.Log import network.nga.sdk.NGASDK object PlayerAccount { fun onSignedIn(accountId: String) { val result = NGASDK.setCustomerUserId(accountId) if (!result.accepted) Log.w("Game", "NGA customer user id: ${result.error?.detail}") } fun onSignedOut() { NGASDK.setCustomerUserId(null) } } ``` **iOS (Swift)** ```swift import NGASDK enum PlayerAccount { static func onSignedIn(accountId: String) { let result = NGASDK.setCustomerUserId(accountId) if !result.accepted { print("NGA customer user id: \(result.error?.detail ?? "")") } } static func onSignedOut() { NGASDK.setCustomerUserId(nil) } } ``` `null` removes the id, for example at sign-out. Without analytics consent, or under child treatment, NGA receives only the fact that an id is set, never the id. The id's format and errors: [`setCustomerUserId`](https://nga.io/docs/sdk/reference/ngasdk/#setcustomeruserid). ## NGA's own impressions One app-wide listener reports every NGA impression with its exact payout, for your own analytics. NGA already records these impressions; do not pass them to `logAdRevenue`. **Unity (C#)** ```csharp using NGA; using UnityEngine; public static class NGAImpressions { // Once, after Initialize. A later call replaces the listener; null removes it. public static void Listen() { NGASDK.SetImpressionListener(imp => Debug.Log($"NGA impression {imp.OpportunityId}: {imp.RevenueMicros} micros {imp.Currency}, " + $"{imp.Format}, promoting {imp.AdvertiserBundle}")); } } ``` **Android (Kotlin)** ```kotlin import android.util.Log import network.nga.sdk.NGASDK object NGAImpressions { // Once, after initialize. A later call replaces the listener; null removes it. fun listen() { NGASDK.setImpressionListener { imp -> Log.i( "Game", "NGA impression ${imp.opportunityId}: ${imp.revenueMicros} micros ${imp.currency}, " + "${imp.format}, promoting ${imp.advertiserBundle}", ) } } } ``` **iOS (Swift)** ```swift import NGASDK enum NGAImpressions { // Once, after initialize. A later assignment replaces the listener; nil removes it. static func listen() { NGASDK.impressionListener = { imp in print("NGA impression \(imp.opportunityId): \(imp.revenueMicros) micros \(imp.currency), " + "\(imp.format.rawValue), promoting \(imp.advertiserBundle ?? "-")") } } } ``` In 0.1.0 every NGA impression promotes one of your own games, so: `revenueMicros` is 0; `precision` is `EXACT`; `advertiserBundle` is the promoted game's store id; `creativeId` is null for the native banner. The fields are on [`NGAImpression`](https://nga.io/docs/sdk/reference/values/#ngaimpression). # Troubleshooting Start from what you see: no ad, no banner, a failed build, no reward. Every error code and detail, with its cause and fix, is on the Errors page of the reference. *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/troubleshooting/* ## No ad shows Read `error.code` and `error.detail` in your `onFailed` or `onShowFailed`, then: | You get | Check | | --- | --- | | `RENDER_NOT_AVAILABLE / render.absent` | `nga-sdk-render` (Android), the `NGASDKRender` product (iOS) or `network.nga.sdk-render` (Unity) is missing from the build. | | `RENDER_NOT_AVAILABLE / render.version_mismatch` | the two libraries are at different versions, or come from two builds of one version (two candidates, or the release and a candidate before 0.1.0-rc.6). Use one release for both. | | `NOT_INITIALIZED` | `initialize` was not called, or it failed. Look at what `onInitialized` reported. | | `INVALID_CONFIG / app_key.*` | the app key is mistyped, from another game, or the release build's package name or bundle id is not the one registered for the game in the portal. | | `INVALID_PLACEMENT` | the placement id is mistyped (`placement.format`), or it is not one of this game's placements in the portal (`placement.unknown`). | | `NO_FILL` | a normal answer: see [No fill while testing](https://nga.io/docs/sdk/testing/#no-fill-while-testing). `retryAfterMillis` says when to ask again. If a game that was served gets only `no_fill.decision` while your portal shows nothing switched off or stopped, NGA may have turned its ads off: ask NGA ([When NGA turns a game off](https://nga.io/docs/sdk/go-live/#when-nga-turns-a-game-off)). | | `DISABLED` | the app key is switched off, or this SDK version or build is retired. Loaded ads expire too. | | `ACTIVITY_NOT_RESUMED` | the screen you passed to `show` is not in front. Show from the screen in front; the ad stays ready. | | `ALREADY_SHOWING` | another NGA ad of the same kind is on screen. Wait for its `onClosed`, or close the banner first. | | `EXPIRED` | the ad was loaded more than 30 minutes ago. Load again. | | `INVALID_SHOW_TARGET` | the window is too small for the banner (`show.target.window_too_small`), or your banner yield's `hide` threw (`show.target.yield_failed`). The ad stays ready. | | `RENDER_FAILED` | the show ended in a failure inside the SDK (`render.crashed`, `render.input`, `render.exception`). Load again; if it repeats, send NGA the `DEBUG` log ([Asking NGA](#asking-nga)). | Every code and detail, with its cause and fix: [Errors](https://nga.io/docs/sdk/reference/errors/). Neither `onLoaded` nor `onFailed` called? Every load calls back exactly once per callback, so check that `loadAd` ran and that your callback object was not replaced. ## The banner does not appear, or appears in the wrong place - **No `onLoaded`.** See *No ad shows* above. Until NGA has first read your game's store listing, its native placements get no fill ([What the banner shows](https://nga.io/docs/sdk/native-cross-promo/#what-the-banner-shows)). - **`show` called, no banner, and `onShowFailed`.** The screen was not in front, another banner was up, or the window is too small. The ad stays ready; the causes, and when to show again, are in [Show lifecycle](https://nga.io/docs/sdk/native-cross-promo/#show-lifecycle). - **The banner covers your own banner ad.** Register the [banner yield](https://nga.io/docs/sdk/native-cross-promo/#your-own-banner-ad) once at start; without it, the first native show logs one `WARN`. With it registered, check that its `hide` reaches the view that is on screen (a banner ad created during a yield starts hidden in the examples). - **Your banner ad does not come back, or stops refreshing, after NGA's banner.** Your `restore` must show it again and resume its refresh whenever the banner is allowed now, not only when it was refreshing at `hide`; see the examples under [Your own banner ad](https://nga.io/docs/sdk/native-cross-promo/#your-own-banner-ad). - **The banner covers your own UI.** Show it only where nothing else is at the bottom of the screen, and call `close()` before you put anything there. The SDK has no position or offset for it. See [Where the banner may show](https://nga.io/docs/sdk/native-cross-promo/#where-the-banner-may-show). - **Unity: the banner stays across scenes.** This is expected. Call `Close()` when you leave the screen that showed it. - **Unity: the game covers the banner.** Turn off *Render Over Native UI*; the build check enforces it. - **`RENDER_FAILED / render.input`.** The banner could not draw what it received. The show ends; load another. - **The banner shows NGA's default colors, not your game's.** NGA could not read colors from your game's listing. Check the game's *Overview* in the portal, which shows what NGA read. ## The build fails - **Unity says `NGA SDK: this build cannot run the NGA SDK.`** Each line names a fix; see [Unity build checks](https://nga.io/docs/sdk/install/#unity-build-checks). - **Unity 2022.3: an Android build stops with `Unity 2022.3… builds this Android release build without minify`** (or `development build`). With 0.1.0-rc.2 or earlier, a release build fails later, at the dexing step, with `ERROR:D8: com.android.tools.r8.kotlin.H` (in `DexingWithClasspathTransform`) on `kotlin-stdlib` or the NGA libraries. Cause: *Minify* is off for that build type (Unity's default). Fix: turn on *Minify > Release*, and *Minify > Debug* for development builds, as in [Install](https://nga.io/docs/sdk/install/#add-the-sdk), step 3 for Unity. - **Unity 2022.3: the Android build fails at the dexing step** after you add MAX 13 or LevelPlay 9.6 or later. Fix: add R8 to `settingsTemplate.gradle`, as in [Install](https://nga.io/docs/sdk/install/#add-the-sdk), step 4 for Unity. - **Unity: the Package Manager cannot add the Git URL.** Cause: Git is not installed or not on the `PATH` Unity sees, or the URL or tag is mistyped. Both URLs end in `#v0.1.0`. - **Unity: `network.nga.sdk-render` fails to resolve `network.nga.sdk`.** Fix: add `network.nga.sdk` from its Git URL too, at the same tag; the render library needs it in your manifest. - **Android: `Could not find network.nga:nga-sdk`.** Cause: `mavenCentral()` is missing from your repositories, or the BOM line is missing: without `platform("network.nga:nga-bom:…")` the two libraries have no version. - **Android: a version conflict on `network.nga:nga-sdk`.** Cause: something pulls another version of the core library beside `nga-sdk-render`, which requires its own. Fix: name one version, through the BOM. - **Android: `NoClassDefFoundError` for a Kotlin, Install Referrer or App Set class at runtime.** Cause: a build rule excluded one of the SDK's dependencies. Fix: remove the exclusion. In Unity, run the External Dependency Manager's *Resolve*. - **Android: a version conflict on `kotlin-stdlib`.** Cause: your build forces a `kotlin-stdlib` older than 1.9. Fix: let Gradle resolve the newer one. - **iOS: Xcode resolves a version other than 0.1.0, or does not offer a release candidate.** Cause: the *Dependency Rule* is a range, which can pick a newer version and skips a release candidate (`-rc.N`, a pre-release). Fix: set the *Dependency Rule* to *Exact Version*. - **iOS: `No such module 'NGASDK'`.** Fix: add the product to the target that imports it. ## No reward - **`onRewardResult` with `granted` false.** The denial says why; see [Rewarded](https://nga.io/docs/sdk/backfill/#rewarded). Tell the player; give nothing. - **No `onRewardResult` at all.** The show ended before its impression counted (`onClosed` alone, or `onShowFailed`), so nothing was earned. Or the placement is an interstitial, which never gets one. - **The game was killed mid-ad.** `onAdClosedAfterRestart` is called at the next launch with the result; see [Rewarded](https://nga.io/docs/sdk/backfill/#rewarded). - **Unity on Android: the reward arrives after the ad closes.** Expected; see [Pause and resume](https://nga.io/docs/sdk/backfill/#pause-and-resume). ## Asking NGA First look at your test device's page in the portal (*Test devices*): its recent ad requests, the reason for each no-fill, and the ad errors it reported. Then write to [hi@nga.network](mailto:hi@nga.network) with your app key, the platform, the SDK version (`NGASDK.getSdkVersion()`), the `code` and `detail`, and the `DEBUG` log from launch to the problem. # Conventions The rules every call follows on every platform, and how names map between Kotlin, Java, Swift, Objective-C and C#. *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/reference/* ## Threads - **Any thread in.** Every public method can be called from any thread, and none blocks it. - **Main thread out.** Every callback and listener is delivered on the main thread (Android, iOS) or Unity's game thread (C#), always asynchronously, never inside the call that caused it, even when the answer is already known. - **Unity on Android.** Unity pauses while NGA's full-screen ad is in front, so that show's callbacks arrive after the ad closes, in their original order, in the first frame after Unity resumes. On iOS they arrive while the ad is on screen. See [Pause and resume](https://nga.io/docs/sdk/backfill/#pause-and-resume). - **Swift 6 language mode.** The examples use Swift 5 mode, the default for existing projects. In Swift 6 mode, a main-actor type (a view controller, your app delegate, a `@MainActor` class) must declare NGA's protocols, and MAX's and LevelPlay's delegates, `@preconcurrency`: `final class GameOverViewController: UIViewController, @preconcurrency NGAAdLoadCallback, @preconcurrency NGAAdShowListener`. The protocols are not actor-isolated, but the SDK calls them only on the main thread. - **Exceptions in callbacks.** The SDK does not catch exceptions your callbacks throw. In Unity they are logged by Unity's own loop, as any exception in a script is. ## Callback ownership The SDK holds every callback strongly (so an inline lambda or block is never collected before it fires) and releases it at a fixed point: | Callback | Released | | --- | --- | | `NGAAdLoadCallback` | after `onFailed`; or when its ad is used, expires or fails; and never later than the ad's expiry (30 minutes for a cross-promo ad) | | `NGAAdShowListener` | after `onClosed` or `onShowFailed` | | `NGAListener` | when a later `initialize` with the same key passes another, non-null listener | A screen registered as a load callback can therefore stay in memory until its ad expires. Either register an app-wide object for loads and pass the screen only as the show listener, or guard callbacks that may arrive after the screen has gone, as the guide's examples do. ## Null arguments A `null` from Java or C#, or `nil` from Objective-C, never throws. It gets the error that call already has for a bad value, such as `INVALID_PLACEMENT / placement.format` for a null placement id; a setter with nothing to report logs a warning and changes nothing. ## Names in each language Types are `NGA`-prefixed and spelled the same on every platform. | | Kotlin | Java | Swift | Objective-C | C# | | --- | --- | --- | --- | --- | --- | | Package or module | `network.nga.sdk` | `network.nga.sdk` | `import NGASDK` | `@import NGASDK;` | `using NGA;` | | Entry point | `NGASDK.loadAd(…)` | `NGASDK.loadAd(…)` (static) | `NGASDK.loadAd(…)` | `[NGASDK loadAd:callback:]` | `NGASDK.LoadAd(…)` | | A property | `error.retryable` | `error.getRetryable()` | `error.retryable` | `error.retryable` | `error.Retryable` | | A ready check | `ad.isReady()` | `ad.isReady()` | `ad.isReady` (property) | `ad.isReady` | `ad.IsReady()` | | An enum case | `NGAErrorCode.NO_FILL` | `NGAErrorCode.NO_FILL` | `.noFill` | `NGAErrorCodeNoFill` | `NGAErrorCode.NoFill` | | A nullable wait | `retryAfterMillis: Long?` | `Long getRetryAfterMillis()` | `retryAfterMillis: Int64?` | `NSNumber *retryAfterMillis` | `long? RetryAfterMillis` | - **Kotlin** properties appear to Java as getters (`granted` becomes `getGranted()`); every method on `NGASDK` is `@JvmStatic`. - **Swift** exports everything to Objective-C; the selectors are on each reference page. - **C#** uses PascalCase members in namespace `NGA`. Interfaces keep the `NGA` name with no `I` prefix. A mediation network keeps its own spelling: `NGAAdRevenueMediation.AdMob`, `Max`, `LevelPlay`. - **No coroutines, Flows, async functions or Tasks.** Every asynchronous answer is a callback. ## Optional methods Some callback methods are optional; the reference marks them. - **Kotlin** interfaces give them empty default bodies, which Java can leave out as well. - **Swift and Objective-C** protocols mark them `optional`. - **C#** interfaces declare every member; implement the optional ones as empty methods. ## Enum integers Every enum has the same cases and the same integers on every platform, and `NGAErrorCode`'s integers are the error table's. Wherever an enum has a safe default (`UNKNOWN`, `NONE` or the least permissive case), it is 0. See [Enums](https://nga.io/docs/sdk/reference/enums/). ## Values the SDK creates `NGAError`, `NGAResult`, `NGAInitResult`, `NGARewardResult`, `NGAImpression` and `NGAAd` come from the SDK; you never need to create one, except in your own tests, where [Testing your own code](https://nga.io/docs/sdk/testing/#testing-your-own-code) says which you can. Every callback for one ad receives the same `NGAAd` object, so you can compare by identity (`===` in Kotlin and Swift) or by `opportunityId`. In C#, `NGAAd` is a sealed class with one instance per ad, and `==`, `Equals` and `GetHashCode` compare `OpportunityId`. ## Java and Objective-C The guide's examples are in C#, Kotlin and Swift. The same calls from Java and Objective-C: **Android (Java)** · `GameApplication.java` ```java import android.app.Application; import android.util.Log; import network.nga.sdk.NGAAd; import network.nga.sdk.NGAAdLoadCallback; 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.NGASDK; public class GameApplication extends Application { @Override public void onCreate() { super.onCreate(); NGAConfig config = new NGAConfig.Builder("app_YOURAPPKEY", NGAConsent.unknown()).build(); NGASDK.initialize(this, config, new NGAListener() { @Override public void onInitialized(NGAInitResult result) { Log.i("Game", "NGA ready: " + result.getSuccess()); } // onError and onAdClosedAfterRestart are optional. }); NGASDK.loadAd("plc_example_interstitial", new NGAAdLoadCallback() { @Override public void onLoaded(NGAAd ad) { Log.i("Game", "loaded " + ad.getOpportunityId()); } @Override public void onFailed(String placementId, NGAError error) { Log.i("Game", "no ad: " + error.getCode() + " / " + error.getDetail()); } // onExpired is optional. }); } } ``` **iOS (Objective-C)** · `GameAppDelegate.m` ```objectivec @import UIKit; @import NGASDK; @interface GameAppDelegate : UIResponder @end @implementation GameAppDelegate - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { NGAConfig *config = [[[NGAConfigBuilder alloc] initWithAppKey:@"app_YOURAPPKEY" consent:[NGAConsent unknown]] build]; [NGASDK initializeWithConfig:config listener:self]; [NGASDK loadAd:@"plc_example_interstitial" callback:self]; return YES; } // NGAListener; onError: and onAdClosedAfterRestartWithPlacementId:opportunityId:rewardGranted: are optional. - (void)onInitialized:(NGAInitResult *)result { NSLog(@"NGA ready: %d", result.success); } // NGAAdLoadCallback; onExpired: is optional. - (void)onLoaded:(id)ad { NSLog(@"loaded %@", ad.opportunityId); } - (void)onFailedWithPlacementId:(NSString *)placementId error:(NGAError *)error { NSLog(@"no ad: %ld / %@", (long)error.code, error.detail); } @end ``` # `NGASDK` The one class you call. Every member is static and may be called from any thread, before `initialize` too, unless its entry says otherwise. *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/reference/ngasdk/* ## `initialize` Starts the SDK with your app key and the player's consent. Call it once per launch, as early as you can. **Unity (C#)** ```csharp public static void Initialize(NGAConfig config, NGAListener listener) ``` **Android (Kotlin)** ```kotlin @JvmStatic fun initialize(context: Context, config: NGAConfig, listener: NGAListener?) ``` **Android (Java)** ```java public static void initialize(Context context, NGAConfig config, NGAListener listener) ``` **iOS (Swift)** ```swift static func initialize(config: NGAConfig, listener: NGAListener?) ``` **iOS (Objective-C)** ```objectivec + (void)initializeWithConfig:(NGAConfig *)config listener:(id)listener; ``` | Name | Required | Description | | --- | --- | --- | | `context` | Android only | your `Application` or any other `Context`. C# passes Unity's Activity for you | | `config` | yes | your app key, the starting consent and test mode; see [`NGAConfig`](https://nga.io/docs/sdk/reference/configuration/#ngaconfig) | | `listener` | no | gets `onInitialized` once for this call, and from then on `onError` and `onAdClosedAfterRestart`. Null keeps the earlier listener | - **Returns:** nothing; the answer is `onInitialized`, on the main thread. - **Errors** (in `NGAInitResult.error`): `INVALID_CONFIG` (`app_key.format`, `app_key.changed`, `app_key.unknown`, `platform.unsupported`), `DISABLED`, `NETWORK / init.unreachable`, `TIMEOUT / init.timeout`, `SERVER_REJECTED`, `INTERNAL / init.parse`. A retryable failure keeps retrying in the background. - **Notes:** a second call: see [Calling `initialize` again](https://nga.io/docs/sdk/initialize/#calling-initialize-again). ## `getSdkVersion` Returns the SDK's version, such as `0.1.0`. **Unity (C#)** ```csharp public static string GetSdkVersion() ``` **Android (Kotlin)** ```kotlin @JvmStatic fun getSdkVersion(): String ``` **Android (Java)** ```java public static String getSdkVersion() ``` **iOS (Swift)** ```swift static func getSdkVersion() -> String ``` **iOS (Objective-C)** ```objectivec + (NSString *)getSdkVersion; ``` - **Returns:** the version, such as `0.1.0`. A release candidate returns its release version, without `-rc.N`: 0.1.0-rc.6 returns `0.1.0`, as 0.1.0 does (see [Install](https://nga.io/docs/sdk/install/#what-you-add)). - **Notes:** include it when you contact NGA. ## `setLogLevel` Sets how much the SDK writes to the device log. Default: `WARN`. **Unity (C#)** ```csharp public static void SetLogLevel(NGALogLevel level) ``` **Android (Kotlin)** ```kotlin @JvmStatic fun setLogLevel(level: NGALogLevel) ``` **Android (Java)** ```java public static void setLogLevel(NGALogLevel level) ``` **iOS (Swift)** ```swift static func setLogLevel(_ level: NGALogLevel) ``` **iOS (Objective-C)** ```objectivec + (void)setLogLevel:(NGALogLevel)level; ``` | Name | Required | Description | | --- | --- | --- | | `level` | yes | [`NGALogLevel`](https://nga.io/docs/sdk/reference/enums/#ngaloglevel): `NONE`, `ERROR`, `WARN`, `INFO` or `DEBUG` | - **Lifetime:** this process. - **Notes:** a `DEBUG` level set before `initialize` covers init. It governs both libraries. Outside test mode no level prints a player's identifiers. ## `setConsent`, `getConsent` Sets the player's consent, and reads the consent in effect. **Unity (C#)** ```csharp public static void SetConsent(NGAConsent consent) public static NGAConsent GetConsent() ``` **Android (Kotlin)** ```kotlin @JvmStatic fun setConsent(consent: NGAConsent) @JvmStatic fun getConsent(): NGAConsent ``` **Android (Java)** ```java public static void setConsent(NGAConsent consent) public static NGAConsent getConsent() ``` **iOS (Swift)** ```swift static func setConsent(_ consent: NGAConsent) static func getConsent() -> NGAConsent ``` **iOS (Objective-C)** ```objectivec + (void)setConsent:(NGAConsent *)consent; + (NGAConsent *)getConsent; ``` | Name | Required | Description | | --- | --- | --- | | `consent` | yes | an [`NGAConsent`](https://nga.io/docs/sdk/reference/configuration/#ngaconsent). Null changes nothing and logs one warning | - **Returns:** `getConsent` returns, per field, the stricter of your answer and the IAB TCF keys. `UNKNOWN` stays `UNKNOWN`; NGA's server applies the regional rule. ATT is not included. It never blocks, and reflects a `setConsent` made just before. - **Lifetime:** saved across launches. - **Notes:** `setConsent` replaces both fields, `UNKNOWN` included, and a change is recorded. How it combines with the builder's consent: [Consent](https://nga.io/docs/sdk/privacy/#consent). ## `setAge`, `getAge` Sets the player's age from your own age gate, and reads it. **Unity (C#)** ```csharp public static void SetAge(NGAAgeState age) public static NGAAgeState GetAge() ``` **Android (Kotlin)** ```kotlin @JvmStatic fun setAge(age: NGAAgeState) @JvmStatic fun getAge(): NGAAgeState ``` **Android (Java)** ```java public static void setAge(NGAAgeState age) public static NGAAgeState getAge() ``` **iOS (Swift)** ```swift static func setAge(_ age: NGAAgeState) static func getAge() -> NGAAgeState ``` **iOS (Objective-C)** ```objectivec + (void)setAge:(NGAAgeState)age; + (NGAAgeState)getAge; ``` | Name | Required | Description | | --- | --- | --- | | `age` | yes | [`NGAAgeState`](https://nga.io/docs/sdk/reference/enums/#ngaagestate): `CHILD` or `ADULT` | - **Returns:** `getAge` returns the age you last set, `UNKNOWN` until you set one. - **Lifetime:** saved across launches. - **Notes:** `setAge` never touches consent. See [Age and audience](https://nga.io/docs/sdk/privacy/#age-and-audience). ## `setCustomerUserId` Attaches your own id for the player, or removes it. **Unity (C#)** ```csharp public static NGAResult SetCustomerUserId(string id) ``` **Android (Kotlin)** ```kotlin @JvmStatic fun setCustomerUserId(id: String?): NGAResult ``` **Android (Java)** ```java public static NGAResult setCustomerUserId(String id) ``` **iOS (Swift)** ```swift @discardableResult static func setCustomerUserId(_ id: String?) -> NGAResult ``` **iOS (Objective-C)** ```objectivec + (NGAResult *)setCustomerUserId:(NSString *)id; ``` | Name | Required | Description | | --- | --- | --- | | `id` | yes | 1 to 128 characters (UTF-16 code units), no NUL character; null removes the id | - **Returns:** an [`NGAResult`](https://nga.io/docs/sdk/reference/values/#ngaresult), immediately. - **Errors:** `INVALID_ARGUMENT / customer_user_id.length` or `customer_user_id.format`; the previous id stays. - **Lifetime:** saved across launches. - **Notes:** NGA stores the id hashed. Without analytics consent, or under child treatment, NGA receives only the fact that an id is set, never the id. ## `logAdRevenue` Records one impression's revenue from a network or mediation the SDK does not capture by itself. **Unity (C#)** ```csharp public static NGAResult LogAdRevenue(NGAAdRevenue revenue) ``` **Android (Kotlin)** ```kotlin @JvmStatic fun logAdRevenue(adRevenue: NGAAdRevenue): NGAResult ``` **Android (Java)** ```java public static NGAResult logAdRevenue(NGAAdRevenue adRevenue) ``` **iOS (Swift)** ```swift @discardableResult static func logAdRevenue(_ adRevenue: NGAAdRevenue) -> NGAResult ``` **iOS (Objective-C)** ```objectivec + (NGAResult *)logAdRevenue:(NGAAdRevenue *)adRevenue; ``` | Name | Required | Description | | --- | --- | --- | | `adRevenue` | yes | an [`NGAAdRevenue`](https://nga.io/docs/sdk/reference/configuration/#ngaadrevenue) | - **Returns:** an [`NGAResult`](https://nga.io/docs/sdk/reference/values/#ngaresult), immediately. - **Errors:** `INVALID_ARGUMENT / ad_revenue.revenue`, `ad_revenue.currency`, `ad_revenue.length`, `argument.null`. - **Notes:** MAX and LevelPlay are captured without this call; logging one of theirs too does no harm with that mediation's own impression id, or none. With an id of your own, NGA keeps both copies. ## `logPurchase` Records a StoreKit 2 purchase, which the SDK cannot always see by itself. iOS and Unity only. **Unity (C#)** ```csharp public static NGAResult LogPurchase(string jws) ``` **iOS (Swift)** ```swift @discardableResult static func logPurchase(_ result: VerificationResult) -> NGAResult ``` | Name | Required | Description | | --- | --- | --- | | `result` (Swift) | yes | the result `Product.purchase()` returned, for every successful purchase | | `jws` (C#) | yes | the order's JWS, `order.Info.Apple.jwsRepresentation` with Unity IAP 5 | - **Returns:** an [`NGAResult`](https://nga.io/docs/sdk/reference/values/#ngaresult), immediately. - **Errors:** `INVALID_ARGUMENT / purchase.jws` (not a StoreKit 2 transaction's JWS), `argument.null` (C#). - **Notes:** a purchase is recorded once even if the SDK also saw it. In C# on Android it records nothing and returns `accepted`. There is no Kotlin, Java or Objective-C version: every Play purchase is captured without a call, and StoreKit 2 has no Objective-C API. ## `loadAd` Loads an ad for a placement. **Unity (C#)** ```csharp public static void LoadAd(string placementId, NGAAdLoadCallback callback) ``` **Android (Kotlin)** ```kotlin @JvmStatic fun loadAd(placementId: String, callback: NGAAdLoadCallback) ``` **Android (Java)** ```java public static void loadAd(String placementId, NGAAdLoadCallback callback) ``` **iOS (Swift)** ```swift static func loadAd(_ placementId: String, callback: NGAAdLoadCallback) ``` **iOS (Objective-C)** ```objectivec + (void)loadAd:(NSString *)placementId callback:(id)callback; ``` | Name | Required | Description | | --- | --- | --- | | `placementId` | yes | `plc_` and 3 to 64 lower-case letters, digits or `_`, the id you gave the placement in the portal | | `callback` | yes | held strongly until `onFailed`, or until its ad is used, expires or fails | - **Returns:** nothing; the answer is `onLoaded` with an [`NGAAd`](https://nga.io/docs/sdk/reference/values/#ngaad), or `onFailed`. - **Errors** (in `onFailed`): `NO_FILL`, `INVALID_PLACEMENT`, `NETWORK`, `TIMEOUT`, `SERVER_REJECTED`, `NOT_INITIALIZED`, `DISABLED`, `RENDER_NOT_AVAILABLE`, `INTERNAL`; the details are on [Errors](https://nga.io/docs/sdk/reference/errors/). - **Notes:** a placement holds at most one live ad. A `loadAd` for a placement that already has a ready ad gets `onLoaded` immediately, with that same ad; one made while a load is in flight is answered by that load. A `loadAd` before `initialize` waits for init. Without the render library, every load fails with `RENDER_NOT_AVAILABLE / render.absent`. A load that does not finish within 60 seconds fails with `TIMEOUT / ad.timeout`. ## `setImpressionListener` Sets the one app-wide listener for NGA's impressions. **Unity (C#)** ```csharp public static void SetImpressionListener(Action listener) ``` **Android (Kotlin)** ```kotlin @JvmStatic fun setImpressionListener(listener: NGAImpressionListener?) fun interface NGAImpressionListener { fun onImpression(impression: NGAImpression) } ``` **Android (Java)** ```java public static void setImpressionListener(NGAImpressionListener listener) ``` **iOS (Swift)** ```swift static var impressionListener: ((NGAImpression) -> Void)? ``` **iOS (Objective-C)** ```objectivec @property (class, nonatomic, copy, nullable) void (^impressionListener)(NGAImpression *); ``` | Name | Required | Description | | --- | --- | --- | | `listener` | yes | called once per impression, after the impression counted, with an [`NGAImpression`](https://nga.io/docs/sdk/reference/values/#ngaimpression). Null removes it | - **Lifetime:** this process. - **Notes:** a later call replaces the listener. It is kept whether or not the render library is present. ## `setMuted`, `isMuted` Mutes or unmutes all NGA ads, and reads the setting. **Unity (C#)** ```csharp public static void SetMuted(bool muted) public static bool IsMuted() ``` **Android (Kotlin)** ```kotlin @JvmStatic fun setMuted(muted: Boolean) @JvmStatic fun isMuted(): Boolean ``` **Android (Java)** ```java public static void setMuted(boolean muted) public static boolean isMuted() ``` **iOS (Swift)** ```swift static func setMuted(_ muted: Bool) static func isMuted() -> Bool ``` **iOS (Objective-C)** ```objectivec + (void)setMuted:(BOOL)muted; + (BOOL)isMuted; ``` | Name | Required | Description | | --- | --- | --- | | `muted` | yes | `true` starts every NGA ad muted; the player can unmute within an ad | - **Returns:** `isMuted` returns the setting. - **Lifetime:** this process. - **Notes:** one setting for the whole app; there is no per-placement mute. It also affects an ad already on screen. Only the ad's own sound changes, never the device volume or your game's audio. Like any video, an ad with sound may pause or duck other apps' audio while it plays. ## `setBannerYield` Registers your own banner ad's `hide` and `restore`, which the SDK runs around every native banner show, or clears them. **Unity (C#)** ```csharp public static void SetBannerYield(Action hide, Action restore) ``` **Android (Kotlin)** ```kotlin @JvmStatic fun setBannerYield(hide: Runnable?, restore: Runnable?) ``` **Android (Java)** ```java public static void setBannerYield(Runnable hide, Runnable restore) ``` **iOS (Swift)** ```swift static func setBannerYield(hide: (() -> Void)?, restore: (() -> Void)?) ``` **iOS (Objective-C)** ```objectivec + (void)setBannerYieldWithHide:(void (^)(void))hide restore:(void (^)(void))restore; ``` | Name | Required | Description | | --- | --- | --- | | `hide` | with `restore` | called once per native banner show, on the main thread (Unity: the game thread), just before NGA's banner is added; it takes your banner ad off the screen and pauses its refresh | | `restore` | with `hide` | called exactly once for each `hide`, after NGA's banner is removed, whatever ended the show; it puts your banner ad back | - **Lifetime:** this process. A later call replaces the pair; both null clears it; one null alone is ignored with one warning. - **Errors:** none returned. A `hide` that throws (in Unity: throws, or is not back within a second) refuses that show with `INVALID_SHOW_TARGET / show.target.yield_failed`: the ad stays `READY`, and `restore` is called. A throw from `restore` is not caught. - **Notes:** kept whether or not the render library is present. With no pair registered, the first native show in the process logs one `WARN`. What each callback does, with an example per mediation and engine: [Your own banner ad](https://nga.io/docs/sdk/native-cross-promo/#your-own-banner-ad). A game with no banner ad never calls this. # Configuration and inputs What you hand the SDK. NGAConfig and NGAConsent at initialize, and NGAAdRevenue for other networks' revenue. *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/reference/configuration/* ## `NGAConfig` Holds what `initialize` needs: the app key, the starting consent and test mode. Everything else (placements, caps, networking) comes from NGA's server. **Unity (C#)** ```csharp new NGAConfig.Builder(string appKey, NGAConsent consent) .TestMode(bool enabled) // optional; default false .Build() // -> NGAConfig ``` **Android (Kotlin)** ```kotlin NGAConfig.Builder(appKey: String, consent: NGAConsent) .testMode(enabled: Boolean) // optional; default false .build() // -> NGAConfig ``` **Android (Java)** ```java new NGAConfig.Builder(String appKey, NGAConsent consent) .testMode(boolean enabled) // optional; default false .build(); // -> NGAConfig ``` **iOS (Swift)** ```swift NGAConfig.Builder(appKey: String, consent: NGAConsent) .testMode(_ enabled: Bool) // optional; default false .build() // -> NGAConfig ``` **iOS (Objective-C)** ```objectivec [[[NGAConfigBuilder alloc] initWithAppKey:(NSString *)appKey consent:(NGAConsent *)consent] testMode:(BOOL)enabled] // optional; default NO build] // -> NGAConfig * ``` | Name | Required | Description | | --- | --- | --- | | `appKey` | yes | `app_` and 8 to 64 letters or digits, the game's key from the portal; the same on Android and iOS | | `consent` | yes | the player's consent as you last stored it, or `NGAConsent.unknown()`. How it combines with `setConsent`: [Consent](https://nga.io/docs/sdk/privacy/#consent) | | `testMode` | no; default false | marks this install's traffic as test. A registered test device does the same; see [Test mode](https://nga.io/docs/sdk/testing/#test-mode) | - **Errors:** the builder validates nothing; `initialize` does, and fails with `INVALID_CONFIG / app_key.format` for a malformed key. - **Notes:** in C#, a built `NGAConfig` also reads back what it holds: `AppKey`, `Consent` and `TestModeEnabled`. ## `NGAConsent` The player's consent: two fields, each an [`NGAConsentState`](https://nga.io/docs/sdk/reference/enums/#ngaconsentstate). **Unity (C#)** ```csharp public sealed class NGAConsent : IEquatable { public NGAConsent(NGAConsentState analytics, NGAConsentState adsPersonalization) public NGAConsentState Analytics { get; } public NGAConsentState AdsPersonalization { get; } public static NGAConsent Unknown() } ``` **Android (Kotlin)** ```kotlin class NGAConsent(val analytics: NGAConsentState, val adsPersonalization: NGAConsentState) { companion object { @JvmStatic fun unknown(): NGAConsent } } ``` **Android (Java)** ```java public NGAConsent(NGAConsentState analytics, NGAConsentState adsPersonalization) public NGAConsentState getAnalytics() public NGAConsentState getAdsPersonalization() public static NGAConsent unknown() ``` **iOS (Swift)** ```swift final class NGAConsent: NSObject { init(analytics: NGAConsentState, adsPersonalization: NGAConsentState) let analytics: NGAConsentState let adsPersonalization: NGAConsentState static func unknown() -> NGAConsent } ``` **iOS (Objective-C)** ```objectivec - (instancetype)initWithAnalytics:(NGAConsentState)analytics adsPersonalization:(NGAConsentState)adsPersonalization; @property (readonly) NGAConsentState analytics; @property (readonly) NGAConsentState adsPersonalization; + (NGAConsent *)unknown; ``` | Name | Required | Description | | --- | --- | --- | | `analytics` | yes | the SDK's collection for your game; what it covers is on [Consent](https://nga.io/docs/sdk/privacy/#consent) | | `adsPersonalization` | yes | NGA's own use of the player's data across games; what it covers is on [Consent](https://nga.io/docs/sdk/privacy/#consent) | - **Notes:** `unknown()` is both fields `UNKNOWN`: "not answered yet". Two `NGAConsent` values with the same fields are equal. How `UNKNOWN` resolves by region, and how the IAB keys combine with your answer: [Consent](https://nga.io/docs/sdk/privacy/#consent). ## `NGAAdRevenue` One impression's revenue from another network, for [`logAdRevenue`](https://nga.io/docs/sdk/reference/ngasdk/#logadrevenue). **Unity (C#)** ```csharp new NGAAdRevenue.Builder(NGAAdRevenueMediation mediation, long revenueMicros, string currency, NGARevenuePrecision precision) .Network(string network) .AdUnitId(string adUnitId) .AdFormat(NGAAdFormat adFormat) .Placement(string placement) .NetworkPlacement(string networkPlacement) .CreativeId(string creativeId) .AdvertiserDomain(string advertiserDomain) .ImpressionId(string impressionId) .Build() // -> NGAAdRevenue ``` **Android (Kotlin)** ```kotlin NGAAdRevenue.Builder(mediation: NGAAdRevenueMediation, revenueMicros: Long, currency: String, precision: NGARevenuePrecision) .network(name: String) .adUnitId(id: String) .adFormat(format: NGAAdFormat) .placement(name: String) .networkPlacement(id: String) .creativeId(id: String) .advertiserDomain(adomain: String) .impressionId(id: String) .build() // -> NGAAdRevenue ``` **Android (Java)** ```java new NGAAdRevenue.Builder(NGAAdRevenueMediation mediation, long revenueMicros, String currency, NGARevenuePrecision precision) .network(String name) .adUnitId(String id) .adFormat(NGAAdFormat format) .placement(String name) .networkPlacement(String id) .creativeId(String id) .advertiserDomain(String adomain) .impressionId(String id) .build(); // -> NGAAdRevenue ``` **iOS (Swift)** ```swift NGAAdRevenue.Builder(mediation: NGAAdRevenueMediation, revenueMicros: Int64, currency: String, precision: NGARevenuePrecision) .network(_ name: String) .adUnitId(_ id: String) .adFormat(_ format: NGAAdFormat) .placement(_ name: String) .networkPlacement(_ id: String) .creativeId(_ id: String) .advertiserDomain(_ adomain: String) .impressionId(_ id: String) .build() // -> NGAAdRevenue ``` **iOS (Objective-C)** ```objectivec [[[NGAAdRevenueBuilder alloc] initWithMediation:(NGAAdRevenueMediation)mediation revenueMicros:(int64_t)revenueMicros currency:(NSString *)currency precision:(NGARevenuePrecision)precision] network:(NSString *)name] // and adUnitId:, adFormat:, placement:, networkPlacement:, build] // creativeId:, advertiserDomain:, impressionId: -> NGAAdRevenue * ``` | Name | Required | Description | | --- | --- | --- | | `mediation` | yes | the layer that served the ad: `ADMOB`, `MAX`, `LEVELPLAY`, `OTHER`, or `NONE` for one network with no mediation | | `revenueMicros` | yes | the revenue in micros, 0 or more; convert a decimal once by rounding: `(revenue * 1_000_000).roundToLong()`. Otherwise `INVALID_ARGUMENT / ad_revenue.revenue` | | `currency` | yes | three letters, sent upper-case. Otherwise `INVALID_ARGUMENT / ad_revenue.currency` | | `precision` | yes | [`NGARevenuePrecision`](https://nga.io/docs/sdk/reference/enums/#ngarevenueprecision), as your network reports it | | `network` | no | the network that served the ad | | `adUnitId` | no | the ad unit in your mediation's dashboard | | `adFormat` | no | [`NGAAdFormat`](https://nga.io/docs/sdk/reference/enums/#ngaadformat) | | `placement` | no | your own name for the spot in the game | | `networkPlacement` | no | the serving network's own placement id | | `creativeId` | no | the creative's id | | `advertiserDomain` | no | the advertiser's domain | | `impressionId` | no | the impression id your mediation assigned | - **Errors:** each string is at most 200 characters; otherwise `INVALID_ARGUMENT / ad_revenue.length`. The builder validates nothing; `logAdRevenue` does. - **Notes:** in C#, a built `NGAAdRevenue` reads back each field as a property of the same name: `Mediation`, `RevenueMicros`, `Currency`, `Precision`, `Network`, `AdUnitId`, `AdFormat`, `Placement`, `NetworkPlacement`, `CreativeId`, `AdvertiserDomain` and `ImpressionId`. # Callbacks The three interfaces you implement. Every method is called on the main thread (in Unity, the game thread), always after the call that caused it has returned. *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/reference/callbacks/* ## `NGAListener` Passed to `initialize`. One per app. **Unity (C#)** ```csharp public interface NGAListener { void OnInitialized(NGAInitResult result); void OnError(NGAError error); // optional: implement empty void OnAdClosedAfterRestart(string placementId, string opportunityId, bool rewardGranted); // optional: implement empty } ``` **Android (Kotlin)** ```kotlin interface NGAListener { fun onInitialized(result: NGAInitResult) fun onError(error: NGAError) {} // optional fun onAdClosedAfterRestart(placementId: String, opportunityId: String, rewardGranted: Boolean) {} // optional } ``` **Android (Java)** ```java public interface NGAListener { void onInitialized(NGAInitResult result); default void onError(NGAError error) {} // optional default void onAdClosedAfterRestart(String placementId, String opportunityId, boolean rewardGranted) {} // optional } ``` **iOS (Swift)** ```swift @objc protocol NGAListener { func onInitialized(_ result: NGAInitResult) @objc optional func onError(_ error: NGAError) @objc optional func onAdClosedAfterRestart(placementId: String, opportunityId: String, rewardGranted: Bool) } ``` **iOS (Objective-C)** ```objectivec @protocol NGAListener - (void)onInitialized:(NGAInitResult *)result; @optional - (void)onError:(NGAError *)error; - (void)onAdClosedAfterRestartWithPlacementId:(NSString *)placementId opportunityId:(NSString *)opportunityId rewardGranted:(BOOL)rewardGranted; @end ``` | Method | Called | | --- | --- | | `onInitialized` | once per `initialize` call, with an [`NGAInitResult`](https://nga.io/docs/sdk/reference/values/#ngainitresult) | | `onError` | after init, only for `DISABLED / app_key.disabled` or `sdk.retired`, `NOT_INITIALIZED / queue.discarded` and `INTERNAL / event_queue.reset`. Not for retries or network errors | | `onAdClosedAfterRestart` | after a successful `onInitialized`, once for each NGA ad that was on screen when the process died. `rewardGranted` is true if a rewarded ad's reward was earned; pay it unless `onRewardResult` already did. The latest 5 reports that come while no listener is set are kept until an `initialize` sets one | ## `NGAAdLoadCallback` Passed to `loadAd`. **Unity (C#)** ```csharp public interface NGAAdLoadCallback { void OnLoaded(NGAAd ad); void OnFailed(string placementId, NGAError error); void OnExpired(NGAAd ad); // optional: implement empty } ``` **Android (Kotlin)** ```kotlin interface NGAAdLoadCallback { fun onLoaded(ad: NGAAd) fun onFailed(placementId: String, error: NGAError) fun onExpired(ad: NGAAd) {} // optional } ``` **Android (Java)** ```java public interface NGAAdLoadCallback { void onLoaded(NGAAd ad); void onFailed(String placementId, NGAError error); default void onExpired(NGAAd ad) {} // optional } ``` **iOS (Swift)** ```swift @objc protocol NGAAdLoadCallback { func onLoaded(_ ad: NGAAd) func onFailed(placementId: String, error: NGAError) @objc optional func onExpired(_ ad: NGAAd) } ``` **iOS (Objective-C)** ```objectivec @protocol NGAAdLoadCallback - (void)onLoaded:(id)ad; - (void)onFailedWithPlacementId:(NSString *)placementId error:(NGAError *)error; @optional - (void)onExpired:(id)ad; @end ``` | Method | Called | | --- | --- | | `onLoaded` | when the ad is cached, verified and ready to show. Every distinct callback passed to `loadAd` for this ad gets it | | `onFailed` | when the load fails. Every callback waiting on the same load gets the same error. `retryable` and `retryAfterMillis` say whether and when to try again | | `onExpired` | when the ad can no longer be shown: it expired, its files were cleared, child treatment began, or NGA stopped the SDK (the app key switched off, or this SDK version or build retired). Not called for an ad that was shown | ## `NGAAdShowListener` Passed to `show`. One per show. **Unity (C#)** ```csharp public interface NGAAdShowListener { void OnShowStarted(NGAAd ad); void OnClicked(NGAAd ad); // optional: implement empty void OnRewardResult(NGAAd ad, NGARewardResult result); // optional: implement empty void OnCompleted(NGAAd ad, NGAShowCompletion completion); void OnClosed(NGAAd ad); void OnShowFailed(NGAAd ad, NGAError error); } ``` **Android (Kotlin)** ```kotlin interface NGAAdShowListener { fun onShowStarted(ad: NGAAd) fun onClicked(ad: NGAAd) {} // optional fun onRewardResult(ad: NGAAd, result: NGARewardResult) {} // optional fun onCompleted(ad: NGAAd, completion: NGAShowCompletion) fun onClosed(ad: NGAAd) fun onShowFailed(ad: NGAAd, error: NGAError) } ``` **Android (Java)** ```java public interface NGAAdShowListener { void onShowStarted(NGAAd ad); default void onClicked(NGAAd ad) {} // optional default void onRewardResult(NGAAd ad, NGARewardResult result) {} // optional void onCompleted(NGAAd ad, NGAShowCompletion completion); void onClosed(NGAAd ad); void onShowFailed(NGAAd ad, NGAError error); } ``` **iOS (Swift)** ```swift @objc protocol NGAAdShowListener { func onShowStarted(_ ad: NGAAd) @objc optional func onClicked(_ ad: NGAAd) @objc optional func onRewardResult(_ ad: NGAAd, result: NGARewardResult) func onCompleted(_ ad: NGAAd, completion: NGAShowCompletion) func onClosed(_ ad: NGAAd) func onShowFailed(_ ad: NGAAd, error: NGAError) } ``` **iOS (Objective-C)** ```objectivec @protocol NGAAdShowListener - (void)onShowStarted:(id)ad; - (void)onCompleted:(id)ad completion:(NGAShowCompletion)completion; - (void)onClosed:(id)ad; - (void)onShowFailed:(id)ad error:(NGAError *)error; @optional - (void)onClicked:(id)ad; - (void)onRewardResult:(id)ad result:(NGARewardResult *)result; @end ``` A show that counts its impression calls these, in this order: | Order | Method | Called | | --- | --- | --- | | 1 | `onShowStarted` | when the impression counted: at least half the ad visible for a second, in the foreground, screen on | | 2 | `onClicked` | zero or more times, once per tap that opens the store | | 3 | `onRewardResult` | rewarded placements only, exactly once, with an [`NGARewardResult`](https://nga.io/docs/sdk/reference/values/#ngarewardresult) | | 4 | `onCompleted` | with `COMPLETED` or `SKIPPED`. A full-screen ad is `COMPLETED` when it was on screen as long as its video; a native banner always is | | 5 | `onClosed` | always last. The ad is used up (`CONSUMED`) | | — | `onShowFailed` | when the show could not start, or it ended in a failure: its renderer crashed and the retry failed, or the SDK's own drawing or screen code failed (`RENDER_FAILED`); nothing follows it | A show that ends before its impression calls `onClosed` alone: nothing is paid and nothing earned. **Every show ends exactly once,** with one `onClosed` or one `onShowFailed`, and nothing follows it. **After `onShowFailed`, the ad's state says what to do.** Check `isReady()`. - `ALREADY_SHOWING` leaves the ad as it was: `READY` when another ad is on screen (`show.already_showing.fullscreen`, `show.already_showing.banner`), `SHOWING` when it is this ad (`show.already_showing.same_handle`). - `ACTIVITY_NOT_RESUMED`, `INVALID_SHOW_TARGET` and `RENDER_NOT_AVAILABLE / webview.unavailable` leave it `READY`: show it again when the cause is gone. - `EXPIRED`, `AD_CONSUMED`, `NOT_READY` and `RENDER_FAILED` mean it is spent: load again. # Values What the SDK hands back. Every value is immutable and safe to read on any thread. *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/reference/values/* ## `NGAAd` One loaded ad, from `onLoaded`. It is single-use: once shown, it is consumed. **Unity (C#)** ```csharp public sealed class NGAAd : IEquatable { public string PlacementId { get; } public string OpportunityId { get; } public long ExpiresAtMillis { get; } public NGAAdState State { get; } public bool IsReady(); public void Show(NGAAdShowListener listener); // every format public void Close(); // the native banner } ``` **Android (Kotlin)** ```kotlin interface NGAAd { val placementId: String val opportunityId: String val expiresAtMillis: Long val state: NGAAdState fun isReady(): Boolean fun show(activity: Activity, listener: NGAAdShowListener) // every format fun close() // the native banner } ``` **Android (Java)** ```java String getPlacementId() String getOpportunityId() long getExpiresAtMillis() NGAAdState getState() boolean isReady() void show(Activity activity, NGAAdShowListener listener) // every format void close() // the native banner ``` **iOS (Swift)** ```swift @objc protocol NGAAd { var placementId: String { get } var opportunityId: String { get } var expiresAtMillis: Int64 { get } var state: NGAAdState { get } var isReady: Bool { get } func show(from viewController: UIViewController, listener: NGAAdShowListener) // every format func close() // the native banner } ``` **iOS (Objective-C)** ```objectivec @protocol NGAAd @property (readonly) NSString *placementId; @property (readonly) NSString *opportunityId; @property (readonly) int64_t expiresAtMillis; @property (readonly) NGAAdState state; @property (readonly) BOOL isReady; - (void)showFromViewController:(UIViewController *)viewController listener:(id)listener; - (void)close; @end ``` | Member | Description | | --- | --- | | `placementId` | the placement it was loaded for | | `opportunityId` | unique to this ad, and single-use: the id to key a reward by, and the id on its `NGAImpression` | | `expiresAtMillis` | when it expires, in epoch milliseconds, for display only; `isReady()` is the check to use | | `state` | [`NGAAdState`](https://nga.io/docs/sdk/reference/enums/#ngaadstate): `READY`, `SHOWING`, `CONSUMED`, `EXPIRED` or `FAILED` | | `isReady()` | true when `state` is `READY` and the ad has not expired; it checks nothing else | | `show(activity)` / `show(from:)` | shows the ad in its placement's format: full screen (interstitial, rewarded) or the [native banner](https://nga.io/docs/sdk/native-cross-promo/) at the bottom of that screen. C# `Show(listener)` uses Unity's own Activity or view controller | | `close()` | ends a native banner's show: the banner slides down, then `onCompleted` and `onClosed` (`onClosed` alone before its impression). Nothing for a full-screen ad, or a banner that is not showing | There is one `show` for every format. Every `show` ends in `onClosed` or `onShowFailed` and never throws; see [`NGAAdShowListener`](https://nga.io/docs/sdk/reference/callbacks/#ngaadshowlistener). `state` and `isReady()` read a snapshot and never block. **Expiry.** An ad can be shown for 30 minutes after it loads. Then it expires: every load callback for it gets `onExpired`, `isReady()` is false, and `show` fails with `EXPIRED`. Load again. An ad already on screen is not affected. Time asleep counts: an ad that ran out while the device slept expires when the game comes back to the front. When NGA stops the SDK (the app key switched off, or this SDK version or build retired), every loaded ad expires at once. ## `NGARewardResult` A rewarded show's outcome, through `onRewardResult`. **Unity (C#)** ```csharp public bool Granted { get; } public NGARewardDenial Denial { get; } // None when granted ``` **Android (Kotlin)** ```kotlin val granted: Boolean val denial: NGARewardDenial? // null when granted ``` **Android (Java)** ```java boolean getGranted() NGARewardDenial getDenial() // null when granted ``` **iOS (Swift)** ```swift let granted: Bool let denial: NGARewardDenial // .none when granted ``` **iOS (Objective-C)** ```objectivec @property (readonly) BOOL granted; @property (readonly) NGARewardDenial denial; // NGARewardDenialNone when granted ``` | Field | Description | | --- | --- | | `granted` | true when the reward was earned | | `denial` | why not, when `granted` is false: `SKIPPED` (closed before the reward was earned), `INTERRUPTED` (the ad stopped mid-way) or `REJECTED` (this ad grants no reward). Null, `.none` or `None` when granted | Your game defines the reward; NGA has no reward type or amount. ## `NGAImpression` One NGA impression and its payout, through the [impression listener](https://nga.io/docs/sdk/reference/ngasdk/#setimpressionlistener). **Unity (C#)** ```csharp public string PlacementId { get; } public string OpportunityId { get; } public NGAAdFormat Format { get; } public long RevenueMicros { get; } public string Currency { get; } public NGARevenuePrecision Precision { get; } public string CampaignId { get; } // may be null public string CreativeId { get; } // may be null public string AdvertiserBundle { get; } // may be null public string AdvertiserDomain { get; } // may be null ``` **Android (Kotlin)** ```kotlin val placementId: String val opportunityId: String val format: NGAAdFormat val revenueMicros: Long val currency: String val precision: NGARevenuePrecision val campaignId: String? val creativeId: String? val advertiserBundle: String? val advertiserDomain: String? ``` **Android (Java)** ```java String getPlacementId() String getOpportunityId() NGAAdFormat getFormat() long getRevenueMicros() String getCurrency() NGARevenuePrecision getPrecision() String getCampaignId() // may be null String getCreativeId() // may be null String getAdvertiserBundle() // may be null String getAdvertiserDomain() // may be null ``` **iOS (Swift)** ```swift let placementId: String let opportunityId: String let format: NGAAdFormat let revenueMicros: Int64 let currency: String let precision: NGARevenuePrecision let campaignId: String? let creativeId: String? let advertiserBundle: String? let advertiserDomain: String? ``` **iOS (Objective-C)** ```objectivec @property (readonly) NSString *placementId; @property (readonly) NSString *opportunityId; @property (readonly) NGAAdFormat format; @property (readonly) int64_t revenueMicros; @property (readonly) NSString *currency; @property (readonly) NGARevenuePrecision precision; @property (readonly, nullable) NSString *campaignId; @property (readonly, nullable) NSString *creativeId; @property (readonly, nullable) NSString *advertiserBundle; @property (readonly, nullable) NSString *advertiserDomain; ``` | Field | Description | | --- | --- | | `placementId`, `opportunityId` | as on the `NGAAd` | | `format` | `INTERSTITIAL`, `REWARDED` or `NATIVE` (the banner) | | `revenueMicros`, `currency` | your payout for this impression, in micros, and its three-letter currency. Cross-promotion of your own games pays 0 | | `precision` | `EXACT` | | `campaignId` | NGA's id for the campaign | | `creativeId` | NGA's id for the creative, which you can quote to report or block one; null for the banner | | `advertiserBundle` | the promoted game's store id: its Android package name or iOS App Store id | | `advertiserDomain` | null in 0.1.0 | ## `NGAError` Every failure. The codes and details are on [Errors](https://nga.io/docs/sdk/reference/errors/). **Unity (C#)** ```csharp public NGAErrorCode Code { get; } public string Detail { get; } public string Message { get; } public bool Retryable { get; } public long? RetryAfterMillis { get; } ``` **Android (Kotlin)** ```kotlin val code: NGAErrorCode val detail: String val message: String val retryable: Boolean val retryAfterMillis: Long? val cause: Throwable? ``` **Android (Java)** ```java NGAErrorCode getCode() String getDetail() String getMessage() boolean getRetryable() Long getRetryAfterMillis() // may be null Throwable getCause() // may be null ``` **iOS (Swift)** ```swift let code: NGAErrorCode let detail: String let message: String let retryable: Bool let retryAfterMillis: Int64? let cause: NSError? ``` **iOS (Objective-C)** ```objectivec @property (readonly) NGAErrorCode code; @property (readonly) NSString *detail; @property (readonly) NSString *message; @property (readonly) BOOL retryable; @property (readonly, nullable) NSNumber *retryAfterMillis; @property (readonly, nullable) NSError *cause; ``` | Field | Description | | --- | --- | | `code` | [`NGAErrorCode`](https://nga.io/docs/sdk/reference/enums/#ngaerrorcode); the same integer on every platform | | `detail` | a stable reason, such as `no_fill.cap`; safe to branch on | | `message` | for people; may change between releases | | `retryable` | whether trying again can help | | `retryAfterMillis` | a sensible wait, when the SDK or the server knows one; otherwise null | | `cause` | the underlying exception, when there is one; not in C# | ## `NGAResult` The immediate result of a call that validates on the spot: `setCustomerUserId`, `logAdRevenue`, `logPurchase`. **Unity (C#)** ```csharp public bool Accepted { get; } public NGAError Error { get; } // null when accepted ``` **Android (Kotlin)** ```kotlin val accepted: Boolean val error: NGAError? ``` **Android (Java)** ```java boolean getAccepted() NGAError getError() // null when accepted ``` **iOS (Swift)** ```swift let accepted: Bool let error: NGAError? ``` **iOS (Objective-C)** ```objectivec @property (readonly) BOOL accepted; @property (readonly, nullable) NGAError *error; ``` | Field | Description | | --- | --- | | `accepted` | true when the call is valid. It is then delivered, at least once, after an init succeeds in this process | | `error` | why the call was refused; null when accepted | ## `NGAInitResult` The result of `initialize`, through `onInitialized`. **Unity (C#)** ```csharp public bool Success { get; } public NGAError Error { get; } // null on success public bool FromCache { get; } ``` **Android (Kotlin)** ```kotlin val success: Boolean val error: NGAError? val fromCache: Boolean ``` **Android (Java)** ```java boolean getSuccess() NGAError getError() // null on success boolean getFromCache() ``` **iOS (Swift)** ```swift let success: Bool let error: NGAError? let fromCache: Bool ``` **iOS (Objective-C)** ```objectivec @property (readonly) BOOL success; @property (readonly, nullable) NGAError *error; @property (readonly) BOOL fromCache; ``` | Field | Description | | --- | --- | | `success` | true when init completed | | `error` | why init failed; null on success | | `fromCache` | true when init used the configuration saved at an earlier launch, online or not; a fresh one is fetched in the background | See [The answer](https://nga.io/docs/sdk/initialize/#the-answer). # Enums Every enum, with its case names in each language and the integer that is the same everywhere. *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/reference/enums/* - **Integer:** the same on every platform ([Enum integers](https://nga.io/docs/sdk/reference/#enum-integers)). Kotlin enums have a `value` property; Swift and C# enums are `Int`-backed, with the integer as their raw value. - **Swift `.none`:** `NGALogLevel.none` and `NGARewardDenial.none` are enum cases. Next to an optional, write the type (`NGARewardDenial.none`) so it is not read as `Optional.none`. ## `NGAConsentState` The player's answer in each field of an `NGAConsent`. | Integer | Kotlin, Java | Swift | Objective-C | C# | | --- | --- | --- | --- | --- | | 0 | `UNKNOWN` | `.unknown` | `NGAConsentStateUnknown` | `Unknown` | | 1 | `GRANTED` | `.granted` | `NGAConsentStateGranted` | `Granted` | | 2 | `DENIED` | `.denied` | `NGAConsentStateDenied` | `Denied` | `UNKNOWN` is "not answered yet"; how it resolves by region: [Consent](https://nga.io/docs/sdk/privacy/#consent). ## `NGAAgeState` The player's age, for `setAge`. | Integer | Kotlin, Java | Swift | Objective-C | C# | | --- | --- | --- | --- | --- | | 0 | `UNKNOWN` | `.unknown` | `NGAAgeStateUnknown` | `Unknown` | | 1 | `ADULT` | `.adult` | `NGAAgeStateAdult` | `Adult` | | 2 | `CHILD` | `.child` | `NGAAgeStateChild` | `Child` | ## `NGALogLevel` How much the SDK writes to the device log, for `setLogLevel`. | Integer | Kotlin, Java | Swift | Objective-C | C# | | --- | --- | --- | --- | --- | | 0 | `NONE` | `.none` | `NGALogLevelNone` | `None` | | 1 | `ERROR` | `.error` | `NGALogLevelError` | `Error` | | 2 | `WARN` | `.warn` | `NGALogLevelWarn` | `Warn` | | 3 | `INFO` | `.info` | `NGALogLevelInfo` | `Info` | | 4 | `DEBUG` | `.debug` | `NGALogLevelDebug` | `Debug` | The default is `WARN`. ## `NGAAdRevenueMediation` The layer that served another network's ad, in `NGAAdRevenue`. | Integer | Kotlin, Java | Swift | Objective-C | C# | | --- | --- | --- | --- | --- | | 0 | `NONE` | `.none` | `NGAAdRevenueMediationNone` | `None` | | 1 | `ADMOB` | `.admob` | `NGAAdRevenueMediationAdmob` | `AdMob` | | 2 | `MAX` | `.max` | `NGAAdRevenueMediationMax` | `Max` | | 3 | `LEVELPLAY` | `.levelplay` | `NGAAdRevenueMediationLevelplay` | `LevelPlay` | | 4 | `OTHER` | `.other` | `NGAAdRevenueMediationOther` | `Other` | `NONE` is an app that shows ads from one network with no mediation layer; name that network with `network(…)`. ## `NGARevenuePrecision` How exact a revenue figure is, in `NGAAdRevenue` and `NGAImpression`. | Integer | Kotlin, Java | Swift | Objective-C | C# | | --- | --- | --- | --- | --- | | 0 | `UNDEFINED` | `.undefined` | `NGARevenuePrecisionUndefined` | `Undefined` | | 1 | `EXACT` | `.exact` | `NGARevenuePrecisionExact` | `Exact` | | 2 | `ESTIMATED` | `.estimated` | `NGARevenuePrecisionEstimated` | `Estimated` | | 3 | `PUBLISHER_DEFINED` | `.publisherDefined` | `NGARevenuePrecisionPublisherDefined` | `PublisherDefined` | NGA's own impressions are always `EXACT`. ## `NGAAdFormat` An ad's format, in `NGAAdRevenue` and `NGAImpression`. | Integer | Kotlin, Java | Swift | Objective-C | C# | | --- | --- | --- | --- | --- | | 0 | `UNKNOWN` | `.unknown` | `NGAAdFormatUnknown` | `Unknown` | | 1 | `BANNER` | `.banner` | `NGAAdFormatBanner` | `Banner` | | 2 | `MREC` | `.mrec` | `NGAAdFormatMrec` | `Mrec` | | 3 | `INTERSTITIAL` | `.interstitial` | `NGAAdFormatInterstitial` | `Interstitial` | | 4 | `REWARDED` | `.rewarded` | `NGAAdFormatRewarded` | `Rewarded` | | 5 | `REWARDED_INTERSTITIAL` | `.rewardedInterstitial` | `NGAAdFormatRewardedInterstitial` | `RewardedInterstitial` | | 6 | `NATIVE` | `.native` | `NGAAdFormatNative` | `Native` | | 7 | `APP_OPEN` | `.appOpen` | `NGAAdFormatAppOpen` | `AppOpen` | The full list is for `NGAAdRevenue`, describing other networks' ads. `UNKNOWN` means not given, or a format the SDK cannot map; it never appears on an `NGAImpression`. NGA's own ads are `INTERSTITIAL`, `REWARDED` and `NATIVE` (the native banner). ## `NGAAdState` Where an `NGAAd` is in its life. | Integer | Kotlin, Java | Swift | Objective-C | C# | | --- | --- | --- | --- | --- | | 0 | `FAILED` | `.failed` | `NGAAdStateFailed` | `Failed` | | 1 | `READY` | `.ready` | `NGAAdStateReady` | `Ready` | | 2 | `SHOWING` | `.showing` | `NGAAdStateShowing` | `Showing` | | 3 | `CONSUMED` | `.consumed` | `NGAAdStateConsumed` | `Consumed` | | 4 | `EXPIRED` | `.expired` | `NGAAdStateExpired` | `Expired` | An ad starts `READY`. `show` makes it `SHOWING`; a show that ends makes it `CONSUMED`. A show refused for a temporary reason (the screen not in front, a window too small for the banner) returns it to `READY`; see [After `onShowFailed`](https://nga.io/docs/sdk/reference/callbacks/#ngaadshowlistener). `EXPIRED` is set when `onExpired` is called; `FAILED` follows a `RENDER_FAILED` show. ## `NGAShowCompletion` How a show ended, in `onCompleted`. | Integer | Kotlin, Java | Swift | Objective-C | C# | | --- | --- | --- | --- | --- | | 0 | `SKIPPED` | `.skipped` | `NGAShowCompletionSkipped` | `Skipped` | | 1 | `COMPLETED` | `.completed` | `NGAShowCompletionCompleted` | `Completed` | ## `NGARewardDenial` Why a reward was not granted, in `NGARewardResult`. | Integer | Kotlin, Java | Swift | Objective-C | C# | | --- | --- | --- | --- | --- | | 0 | — (`denial` is `null` when granted) | `.none` | `NGARewardDenialNone` | `None` | | 1 | `SKIPPED` | `.skipped` | `NGARewardDenialSkipped` | `Skipped` | | 2 | `REJECTED` | `.rejected` | `NGARewardDenialRejected` | `Rejected` | | 3 | `INTERRUPTED` | `.interrupted` | `NGARewardDenialInterrupted` | `Interrupted` | ## `NGAErrorCode` The code of an `NGAError`. The codes and their integers are on [Errors](https://nga.io/docs/sdk/reference/errors/). # Errors One numbered table on every platform. Every error is an NGAError with a code, a stable detail string, its cause and fix, and whether trying again can help. *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/reference/errors/* ## Codes The integers never change, and a new code takes the next free integer in its range: - 1xx: integration and configuration; you fix these. - 2xx: network, server and internal; usually temporary. - 3xx: loading and showing ads. | Integer | Kotlin, Java | Swift | Objective-C | C# | | --- | --- | --- | --- | --- | | 100 | `NOT_INITIALIZED` | `.notInitialized` | `NGAErrorCodeNotInitialized` | `NotInitialized` | | 101 | `INVALID_CONFIG` | `.invalidConfig` | `NGAErrorCodeInvalidConfig` | `InvalidConfig` | | 102 | `INVALID_ARGUMENT` | `.invalidArgument` | `NGAErrorCodeInvalidArgument` | `InvalidArgument` | | 103 | `DISABLED` | `.disabled` | `NGAErrorCodeDisabled` | `Disabled` | | 104 | `RENDER_NOT_AVAILABLE` | `.renderNotAvailable` | `NGAErrorCodeRenderNotAvailable` | `RenderNotAvailable` | | 200 | `NETWORK` | `.network` | `NGAErrorCodeNetwork` | `Network` | | 201 | `TIMEOUT` | `.timeout` | `NGAErrorCodeTimeout` | `Timeout` | | 202 | `SERVER_REJECTED` | `.serverRejected` | `NGAErrorCodeServerRejected` | `ServerRejected` | | 299 | `INTERNAL` | `.internal` | `NGAErrorCodeInternal` | `Internal` | | 300 | `INVALID_PLACEMENT` | `.invalidPlacement` | `NGAErrorCodeInvalidPlacement` | `InvalidPlacement` | | 301 | `NO_FILL` | `.noFill` | `NGAErrorCodeNoFill` | `NoFill` | | 302 | `EXPIRED` | `.expired` | `NGAErrorCodeExpired` | `Expired` | | 303 | `AD_CONSUMED` | `.adConsumed` | `NGAErrorCodeAdConsumed` | `AdConsumed` | | 304 | `NOT_READY` | `.notReady` | `NGAErrorCodeNotReady` | `NotReady` | | 305 | `ALREADY_SHOWING` | `.alreadyShowing` | `NGAErrorCodeAlreadyShowing` | `AlreadyShowing` | | 306 | `ACTIVITY_NOT_RESUMED` | `.activityNotResumed` | `NGAErrorCodeActivityNotResumed` | `ActivityNotResumed` | | 307 | `RENDER_FAILED` | `.renderFailed` | `NGAErrorCodeRenderFailed` | `RenderFailed` | | 308 | `INVALID_SHOW_TARGET` | `.invalidShowTarget` | `NGAErrorCodeInvalidShowTarget` | `InvalidShowTarget` | To log a code's name: `code.name` (Kotlin, Swift) returns the Kotlin-column name, such as `NO_FILL`; `Code.ToString()` (C#) returns the C# name. The `detail` strings are stable too: branch on them. ## Details One row per `detail`: where it is raised, its cause, its fix, and whether a retry can help. ### Integration and configuration (1xx) | Code | `detail` | Raised by | Cause | Fix | `retryable` | | --- | --- | --- | --- | --- | --- | | `NOT_INITIALIZED` 100 | `queue.full` | any call with a callback, before init | 200 calls were already waiting for init | call `initialize` first; look for a call in a loop | no | | | `init.failed` | calls that waited for a failed init | init failed; the call that waited for it gets this | if `retryable`, init keeps retrying on its own: call again later; otherwise fix what `onInitialized` reported | yes after a retryable init failure; otherwise no | | | `queue.discarded` | `onError` | init failed permanently, and the calls waiting for it were thrown away; the message gives the count | fix the app key; those calls then work | no | | `INVALID_CONFIG` 101 | `app_key.format` | `initialize` | the key is not `app_` and 8 to 64 letters or digits, or is null | use the game's key from the portal | no | | | `app_key.changed` | `initialize` | `initialize` again with another key | one key per game, on both platforms | no | | | `app_key.unknown` | `initialize` | the server does not know the key, the game is not registered for this build's platform, or this release build's package name or bundle id is not the one registered for the game | check the key; add the platform on the game's *Overview*; check its *Store and builds* in the portal | no | | | `platform.unsupported` | `initialize` | an Android process other than the main one, an iOS app extension, or Unity outside an Android or iOS player (the Editor) | initialize in the main app; test Unity on a device | no | | `INVALID_ARGUMENT` 102 | `ad_revenue.revenue` | `logAdRevenue` | `revenueMicros` below 0 | pass 0 or more | no | | | `ad_revenue.currency` | `logAdRevenue` | not three letters | pass the ISO code, such as `USD` | no | | | `ad_revenue.length` | `logAdRevenue` | a string field over 200 characters | shorten it | no | | | `customer_user_id.length` | `setCustomerUserId` | empty, or over 128 characters | pass 1 to 128 characters, or null to remove the id | no | | | `customer_user_id.format` | `setCustomerUserId` | contains a NUL character | remove it | no | | | `purchase.jws` | `logPurchase` (iOS, C#) | the string is not a StoreKit 2 transaction's JWS | pass `jwsRepresentation` from the order | no | | | `argument.null` | `logAdRevenue`, C# `LogPurchase` | null was passed | pass a value | no | | `DISABLED` 103 | `app_key.disabled` | `initialize`, `loadAd`, `onError` | the app key is switched off; collection stops, and loaded ads expire | contact NGA; the SDK resumes at the next launch or foreground once the key is on | no | | | `sdk.retired` | `initialize`, `loadAd`, `onError` | NGA has retired this SDK version or build; loaded ads expire | update the SDK | no | | `RENDER_NOT_AVAILABLE` 104 | `render.absent` | `loadAd` | the render library is not in the build | add it ([Install](https://nga.io/docs/sdk/install/)) | no | | | `render.version_mismatch` | `loadAd` | the render library is at another version than the core library, or, from 0.1.0-rc.3 on, from another build of that version (two candidates, or the release and a candidate before 0.1.0-rc.6); everything else works | use one version, from one release, for both | no | | | `render.init_failed` | `loadAd` | the render library failed to start | update both libraries; contact NGA | no | | | `webview.unavailable` | full-screen `loadAd` and `show` (Android) | no usable WebView right now: missing, disabled or updating | try again later; the banner is unaffected | yes | ### Network and server (2xx) | Code | `detail` | Raised by | Cause | Fix | `retryable` | | --- | --- | --- | --- | --- | --- | | `NETWORK` 200 | `init.unreachable` | `initialize` | no network at init, and no saved configuration | none: init keeps retrying | yes | | | `ad.unreachable` | `loadAd` | the ad request could not be sent | load again later | yes | | | `asset.download` | `loadAd` | an ad's file download was cut short | load again later; files already fetched are kept | yes | | `TIMEOUT` 201 | `init.timeout` | `initialize` | init timed out, and no saved configuration | none: init keeps retrying | yes | | | `ad.timeout` | `loadAd` | the ad and its files did not arrive within 60 seconds | load again later | yes | | `SERVER_REJECTED` 202 | `init.http_NNN` | `initialize` | init was answered with HTTP status *NNN* | none: init keeps retrying | yes | | | `config.signature`, `config.key_unknown` | `initialize` | the configuration NGA sent could not be verified | none: init keeps retrying; contact NGA if it persists | yes | | | `ad.http_NNN` | `loadAd` | the ad request was answered with HTTP status *NNN* | load again later for a 5xx; otherwise contact NGA | yes for a 5xx; otherwise no | | | `ad.schema` | `loadAd` | the ad NGA sent is incomplete | load again later; contact NGA if it persists | yes | | | `asset.hash` | `loadAd` | a downloaded file did not match | contact NGA | no | | `INTERNAL` 299 | `init.parse` | `initialize` | NGA's configuration did not parse | none: init keeps retrying | yes | | | `event_queue.reset` | `onError` | the SDK's event store was damaged on the device and has been reset | none: collection continues | no | | | `cache.write` | `loadAd` | an ad's files could not be saved, for example the disk is full | load again later | yes | `init.http_NNN` and `ad.http_NNN` carry the HTTP status in place of `NNN`, for example `ad.http_503`. ### Loading and showing ads (3xx) | Code | `detail` | Raised by | Cause | Fix | `retryable` | | --- | --- | --- | --- | --- | --- | | `INVALID_PLACEMENT` 300 | `placement.format` | `loadAd` | the id is not `plc_` and 3 to 64 lower-case letters, digits or `_`, or is null | use the placement's id from the portal | no | | | `placement.unknown` | `loadAd` | not one of this game's placements | check the id against the game's *Placements*; a placement you have just added reaches the game at its next launch | yes, with no wait | | `NO_FILL` 301 | `no_fill.decision` | `loadAd` | NGA had no ad for this request | load again after `retryAfterMillis` | yes, after `retryAfterMillis` when it is set | | | `no_fill.cap` | `loadAd` | the placement is at one of its [caps](https://nga.io/docs/sdk/portal/#caps) | `retryAfterMillis` says when it reopens; null for a per-session cap | yes, after `retryAfterMillis` when it is set | | | `no_fill.unsupported` | `loadAd` | the ad needs a newer SDK | update the SDK | yes, after `retryAfterMillis` when it is set | | | `no_fill.rate_limited` | `loadAd` | too many requests | load again after `retryAfterMillis` | yes, after `retryAfterMillis` when it is set | | `EXPIRED` 302 | `show.state.expired` | `show` | shown after it expired, or its files were cleared from the device's cache | load again | no | | `AD_CONSUMED` 303 | `show.state.consumed` | `show` | this ad was already shown | load again | no | | `NOT_READY` 304 | `show.state.failed` | `show` | this ad failed earlier | load again | no | | `ALREADY_SHOWING` 305 | `show.already_showing.same_handle` | `show` | this ad is already showing | wait for its `onClosed` | no | | | `show.already_showing.fullscreen` | `show` | another NGA full-screen ad is on screen | wait for its `onClosed`; this ad stays ready | no | | | `show.already_showing.banner` | `show` | another native banner is on screen | close it, or wait for its `onClosed`; this ad stays ready | no | | `ACTIVITY_NOT_RESUMED` 306 | `show.activity.not_resumed` | `show` | the Activity or view controller passed to `show` cannot present now, or is null | show from the screen in front; the ad stays ready | no | | `RENDER_FAILED` 307 | `render.crashed` | `show` | the ad's renderer stopped and a second try failed; an impression or reward already counted stands | load again | no | | | `render.input` | `show` | the banner could not draw what it received | load again | no | | | `render.exception` | `show` | a failure inside the SDK's own drawing or screen code ended the show, before or after its impression; an impression already counted stands | load again; contact NGA if it repeats | no | | `INVALID_SHOW_TARGET` 308 | `show.target.window_too_small` | `show` (the banner) | the window is under 320 × 133 dp | show it when the window is bigger; the ad stays ready | no | | | `show.target.yield_failed` | `show` (the banner) | your [banner yield](https://nga.io/docs/sdk/native-cross-promo/#your-own-banner-ad)'s `hide` threw, or in Unity was not back within a second | fix `hide`; `restore` was called, and the ad stays ready | no | Every show error has `retryable` false except `webview.unavailable`. What a refused show leaves behind: [After `onShowFailed`](https://nga.io/docs/sdk/reference/callbacks/#ngaadshowlistener). ## `retryAfterMillis` Set only when a wait is known: - `NO_FILL` from the server: the server's wait. - `NO_FILL / no_fill.cap`: the time until a per-day or minimum-interval cap reopens. Null for a per-session cap, which reopens at the next session. - A `loadAd` during a server's wait fails immediately with `NO_FILL` and the time remaining, and sends no request. **Retrying a load yourself:** only when `retryAfterMillis` is set, and only after it passes. The SDK retries on its own for placements with prefetch on and for retryable init failures. ## Where errors arrive | Call | Errors reach you through | | --- | --- | | `initialize` | `onInitialized(result)`, as `result.error` | | after init | `NGAListener.onError` | | `loadAd` | `onFailed(placementId, error)` | | `show` | `onShowFailed(ad, error)` | | `setCustomerUserId`, `logAdRevenue`, `logPurchase` | the returned `NGAResult`'s `error` | No call throws. # Changelog Every release of the NGA SDK, newest first, after the support terms. Until 1.0, a minor release may change the API, with migration notes here. *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/changelog/* ## Support Each release is supported as the NGA SDK License that came with it says; a release that brings a new version of the license says so in its entry. - **0.1.0-rc.4 and later**, until a release's entry names a new license ([License 1.1](https://nga.io/legal/sdk-license/)): a supported version keeps working with NGA's services and receives critical and security fixes, but not new features. A preview or release-candidate version (any 0.x version, and any `-rc.N`) is supported until NGA makes its next version generally available, whether a preview, a release candidate or a stable version, and for 3 months after that. From the first stable version, 1.0, each minor version is supported for at least 24 months after its release, and NGA gives at least 6 months' notice before retiring one. Support applies only while the NGA services the version works with remain available. - **0.1.0-rc.1 to 0.1.0-rc.3** ([License 1.0](https://nga.io/legal/sdk-license/1.0/)): each minor version is supported for at least 24 months after its release, and NGA gives at least 6 months' notice before retiring one. So 0.1.0, the release and not a candidate, is still a 0.x version, and is supported as a preview version: until NGA makes its next version generally available, whether a preview, a release candidate or a stable version, and for 3 months after that. 0.1.0-rc.6 is supported until 3 months after NGA makes 0.1.0 generally available. Under either license, NGA may stop a version at once when that is needed to protect players, studios or NGA's services; see [SDK versions](https://nga.io/docs/sdk/go-live/#sdk-versions). ## 0.1.0 — the release, after six release candidates Published 2026-11-23. 0.1.0 is the build of 0.1.0-rc.6, published again under the plain version, and no longer as a pre-release: `network.nga:nga-bom:0.1.0` on Maven Central, and the tag `v0.1.0` of NGA's Swift package and Unity repository. There is no code change from 0.1.0-rc.6: the libraries are the same, and `getSdkVersion()` returns `0.1.0`, as every candidate did. The public API is unchanged. **What a game must do** - **Update the version** to 0.1.0: the BOM's version on Android, the Swift package's exact version, or the tag in both Unity Git URLs, in one edit. See [Updating](https://nga.io/docs/sdk/install/#updating). - Nothing else from 0.1.0-rc.6, which is the same build. From an earlier candidate, read each entry below since yours: from 0.1.0-rc.3, 0.1.0-rc.4 or 0.1.0-rc.5 they ask for nothing more; from 0.1.0-rc.2 or earlier, also do each one's *What a game must do*. **What changed for a game** - **0.1.0 is the release, not a release candidate.** It is published under its plain version on Maven Central, and as a release, not a pre-release, on the GitHub releases of NGA's Swift package and Unity repository. - **Support.** 0.1.0 comes with version 1.1 of the [NGA SDK License](https://nga.io/legal/sdk-license/), as 0.1.0-rc.4 to 0.1.0-rc.6 did. As a 0.x version it is a preview version under the license: it is supported until NGA makes its next version generally available, whether a preview, a release candidate or a stable version, and for 3 months after that. Under License 1.1, the 24 months for each minor version apply from 1.0 on, not to 0.x versions. With 0.1.0 published, 0.1.0-rc.6 is supported until 3 months after NGA makes 0.1.0 generally available. See [Support](#support). ## 0.1.0-rc.6 — sixth release candidate of 0.1.0 Published 2026-11-22. The build is still 0.1.0: `getSdkVersion()` returns `0.1.0`, and only the coordinates and tags change, from `-rc.5` to `-rc.6`. The public API is unchanged. **What a game must do** - **Update the version**: the BOM's version on Android, the Swift package's exact version, or the tag in both Unity Git URLs, in one edit. See [Updating](https://nga.io/docs/sdk/install/#updating). - Nothing else. A game on 0.1.0-rc.5 needs no other change. **What changed for a game** - **Android: native ads and sessions stay right when a screen behind yours closes late, or another SDK's full-screen ad closes.** If your game called `initialize` while a screen behind its own was still closing (a launcher or splash screen, on a slow phone), or showed another SDK's full-screen ad that lets your screen show through (AdMob's interstitials, rewarded and app-open ads do), the SDK could take your game for being in the background while the player was playing. Every native cross-promo show was then refused with `ACTIVITY_NOT_RESUMED` until the player left the game and came back, a banner already on screen was never counted, and a session pause was recorded with the game in front. Your session figures in the portal were off with it: playing time counted as time away, a long session could be cut in two, and the SDK held its events back as it does in the background, until the player left and came back. Fixed: only the game really leaving the screen pauses the session. - **iOS: a restored purchase is no longer recorded as a new one.** When a player restores purchases with StoreKit 1, the SDK used to record each restored transaction as a new purchase. It no longer does; a purchase approved after Ask to Buy is still recorded once. One case remains: after a reinstall, a restored subscription's latest period can be recorded once, if the SDK had not seen it before; NGA counts each transaction once across installs. - **The native cross-promo banner shows on narrow screens.** On a window 320 to 335 dp (points on iOS) wide, such as the first iPhone SE, an iPhone in Display Zoom, a phone at its largest display size, or a narrow Slide Over window on iPad, the banner used to refuse every show as too small. It now shows, running closer to the edges; only a window under 320 × 133 is too small. See [Show lifecycle](https://nga.io/docs/sdk/native-cross-promo/#show-lifecycle). - **Android: the banner's close works while another app draws over your game.** With a screen dimmer, a chat head or another app's overlay on screen, the player's tap on the banner's close was ignored. It now closes the banner. A tap on the ad itself under such an overlay is still not taken as a click. ## 0.1.0-rc.5 — fifth release candidate of 0.1.0 Published 2026-11-17. The build is still 0.1.0: `getSdkVersion()` returns `0.1.0`, and only the coordinates and tags change, from `-rc.4` to `-rc.5`. The public API is unchanged. **What a game must do** - **Update the version**: the BOM's version on Android, the Swift package's exact version, or the tag in both Unity Git URLs, in one edit. See [Updating](https://nga.io/docs/sdk/install/#updating). - Nothing else. A game on 0.1.0-rc.4 needs no other change. **What changed for a game** - **A faster start on both platforms.** The SDK now builds itself on its own thread, not on yours, so `initialize` costs your thread less: after an earlier SDK call it returns in under a millisecond, and as the first SDK call in the process, which also loads the SDK's classes, it is much faster than before (on a Galaxy A16, from about 40 ms to about 13, the median of five passes). On Android the first call starts one thread and waits for none. Your release build's R8 no longer merges NGA's classes with other libraries' (they are still renamed and removed as before), so fewer classes load on that first call; the SDK's share of a minified app grows by about 100 KB of dex as a result. On iOS, the SDK reads the device's keyboards in a short step of its own after the start. A launch that starts from the SDK's saved configuration now writes to disk once. - **iOS: the native cross-promo banner draws in shorter steps.** Its text is fitted off the main thread with its images; the banner is built in one step and slides in the next; the App Store sheet behind it loads once the banner is on screen. On an iPhone 7, the banner's longest step on the main thread went from about 18 ms to about 5. Your banner yield's `hide` and `restore` are called exactly as before. - **Android: privacy choices are kept while the device's storage is unavailable.** When the SDK cannot write its files yet (a phone still locked after a restart, a full disk), a `setConsent`, `setAge` or `setCustomerUserId` you make still takes effect at once, and is saved as soon as storage is available. Before, such a choice could be replaced by the one saved earlier. `onInitialized` is always called. See [Calls before `initialize`](https://nga.io/docs/sdk/initialize/#calls-before-initialize). - **iOS: a phone set up from another phone starts fresh.** When your game's files arrive on a new iPhone without the SDK's Keychain item (Quick Start, for example), the SDK treats it as a new install: it neither uses the old phone's saved configuration nor a stop NGA had sent it. - **Android: a full-screen ad that fails to appear no longer keeps its WebView** in memory. ## 0.1.0-rc.4 — fourth release candidate of 0.1.0 Published 2026-11-14. The build is still 0.1.0: `getSdkVersion()` returns `0.1.0`, and only the coordinates and tags change, from `-rc.3` to `-rc.4`. The public API is unchanged. **What a game must do** - **Update the version**: the BOM's version on Android, the Swift package's exact version, or the tag in both Unity Git URLs, in one edit. See [Updating](https://nga.io/docs/sdk/install/#updating). - Nothing else. A game on 0.1.0-rc.3 needs no other change. **What changed for a game** - **iOS: an ATT answer is picked up within seconds.** When your game becomes active and the ATT status still reads not determined, the SDK reads it again 1 s, 2.5 s and 5 s later. iOS can deliver the player's answer to your prompt a moment after your game is active again; until now such an answer waited for the SDK's next send of events. See [App Tracking Transparency](https://nga.io/docs/sdk/privacy/#app-tracking-transparency). - **The NGA SDK License 1.1.** This candidate comes with version 1.1 of the [NGA SDK License](https://nga.io/legal/sdk-license/): in the `LICENSE` of the Swift package and of each Unity package, and linked from the Maven POMs. It also sets the support of a preview or release-candidate version: until NGA makes its next version generally available, and 3 months after. Earlier candidates came with [version 1.0](https://nga.io/legal/sdk-license/1.0/), which still governs them. - **iOS: a few more `DEBUG` lines** for NGA's support: one when the SDK holds back a send of queued events, saying why (a request past its deadline among the reasons), and two timing the SDK's read of the device's details. They name no identifier, and appear only at `DEBUG`. ## 0.1.0-rc.3 — third release candidate of 0.1.0 Published 2026-11-10. The build is still 0.1.0: `getSdkVersion()` returns `0.1.0`, and only the coordinates and tags change, from `-rc.2` to `-rc.3`. The public API is unchanged. **What a game must do** - **Update the version**: the BOM's version on Android, the Swift package's exact version, or the tag in both Unity Git URLs, in one edit. See [Updating](https://nga.io/docs/sdk/install/#updating). - **Unity 2022.3, Android: turn on *Minify* for development builds too.** The build check now fails a 2022.3 Android build whose *Minify* is off for its build type, *Release* for a release build and *Debug* for a development build, unless the project puts R8 8 or later on its build classpath. See [Install](https://nga.io/docs/sdk/install/#add-the-sdk), step 3 for Unity. - Nothing else. A game that loaded ads, showed them and registered its banner yield on 0.1.0-rc.2 needs no other change. **What changed for a game** - **The SDK's own loads wait while the app is in the background.** Prefetch, auto-reload and the SDK's refills start no load while the app is behind, and start when it comes to the front. So a process started in the background, by a push, a job or a broadcast receiver, requests and downloads no ad of its own until then. A `loadAd` your game makes is never held. See [Placements](https://nga.io/docs/sdk/portal/#placements). - **A stop ends ready ads.** When NGA switches your app key off or retires your SDK version or build, every loaded ad expires at once (`onExpired`), a native banner on screen closes (`onClosed`), and a full-screen ad already on screen plays to its end. See [When NGA turns a game off](https://nga.io/docs/sdk/go-live/#when-nga-turns-a-game-off). - **Unity: a mixed pair is caught at build time.** Each package now carries the id of the native build it came from. With `network.nga.sdk` at this candidate or later, a build whose two packages are at one version but from different candidates fails, naming both builds; on a device, such a pair answers every ad call `RENDER_NOT_AVAILABLE / render.version_mismatch`, and everything else works. A `network.nga.sdk` at 0.1.0-rc.2 does not catch a newer `network.nga.sdk-render`, so still change both lines in one edit. See [Unity build checks](https://nga.io/docs/sdk/install/#unity-build-checks). - **Going back to an older SDK is safe.** From this candidate on, an SDK that finds files a newer SDK saved on the device in a shape it does not know sets them aside and starts as a new install there, instead of misreading them. See [Updating](https://nga.io/docs/sdk/install/#updating). - **Android: a renamed main process is supported.** An app that names its main process with `android:process` on `` initializes in that process. Other processes still get `INVALID_CONFIG / platform.unsupported`. - **`onAdClosedAfterRestart` is not lost before `initialize`.** The latest 5 reports that arrive before a listener is set are kept, and delivered after the `onInitialized` of the `initialize` call that sets one. - **A new show error: `RENDER_FAILED / render.exception`.** A failure inside the SDK's own drawing or screen code ends that show, with `onShowFailed`, instead of reaching your game. Load again. See [Errors](https://nga.io/docs/sdk/reference/errors/#loading-and-showing-ads-3xx). - **Log lines.** The `WARN` that the render library is not in the build now comes once, at `initialize`, and only when it is missing; a setter called before `initialize` no longer logs it. The `DEBUG` line for a served load names the game it promotes, and a load answered by another load in flight, or waiting for a retry, says so. See [The log](https://nga.io/docs/sdk/testing/#the-log). ## 0.1.0-rc.2 — second release candidate of 0.1.0 Published 2026-11-09. The build is still 0.1.0: `getSdkVersion()` returns `0.1.0`, and only the coordinates and tags change, from `-rc.1` to `-rc.2`. **What a game must do** - **Update the version**: the BOM's version on Android, the Swift package's exact version, or the tag in both Unity Git URLs. See [Updating](https://nga.io/docs/sdk/install/#updating). - **Unity: move both packages together.** `network.nga.sdk` and `network.nga.sdk-render` are built as 0.1.0 in both candidates, so in this candidate a mixed pair passed the build check and `initialize`, and failed at the first native banner show. Change both lines of `Packages/manifest.json` in one edit, and let the Package Manager resolve both before you build. - **Register a banner yield if your game shows a banner ad**: `setBannerYield(hide, restore)`, once at start, with the `hide` and `restore` for your mediation and engine on [Your own banner ad](https://nga.io/docs/sdk/native-cross-promo/#your-own-banner-ad). A game with no banner ad registers none. Nothing else changes in the API or in your integration. **What changed for a game** - **The banner yield.** Just before NGA's native banner draws, the SDK calls the `hide` you registered, which takes your banner ad off the screen; when the show ends, however it ends, it calls your `restore` once. A `hide` that throws refuses the show with `INVALID_SHOW_TARGET / show.target.yield_failed` and the ad stays ready. With no yield registered, the first native show in the process logs one `WARN`. See [`setBannerYield`](https://nga.io/docs/sdk/reference/ngasdk/#setbanneryield). - **The banner shows after a late `initialize`** (Android). A game that calls `initialize` once its consent platform has answered, with its screen already in front, now shows the banner on that screen. In the first candidate the show was refused with `ACTIVITY_NOT_RESUMED` until that screen had paused and resumed once. - **The test-device id line says what the id covers**: `it covers all your games on this device` for a Google Play install and on iOS, `it covers this game only (this build was not installed by Google Play)` for an Android build installed any other way, whose id you register per game. See [Register a test device](https://nga.io/docs/sdk/testing/#register-a-test-device). - **More `DEBUG` lines.** The init summary says whether test mode is on and why; after init there is one line per `loadAd` outcome, one per refused `show`, and one at each show's start and end, with what ended it. None names an identifier. See [The log](https://nga.io/docs/sdk/testing/#the-log). - **A build id.** Each library carries the id of the build it came from and sends it with its requests, so NGA can retire one build without retiring the version. A retired build fails as a retired version does: `DISABLED / sdk.retired` through `onError`. See [SDK versions](https://nga.io/docs/sdk/go-live/#sdk-versions). - **Ad revenue.** A MAX or LevelPlay impression reported without a precision is now recorded, with the precision unknown; one reported without a revenue value is not. - **Unity 2022.3 Android release builds still need *Minify > Release* on**; see [Install](https://nga.io/docs/sdk/install/#add-the-sdk), step 3 for Unity. **Known in this candidate** (fixed in 0.1.0-rc.3) - `setBannerYield` called before `initialize` logs `setBannerYield kept, but nga-sdk-render is not in this build: no NGA ad will show` (on iOS, `NGASDKRender`) even when the render library is in the build: the SDK has not looked for it yet. The yield is kept and works. ## 0.1.0-rc.1 — first release candidate of 0.1.0 First public release, during the preview. **Install** - At 0.1.0-rc.1: Maven Central (`network.nga:nga-bom`, `nga-sdk`, `nga-sdk-render`), Swift Package Manager (`https://github.com/nga-io/nga-sdk-ios`, products `NGASDK` and `NGASDKRender`) and Unity's Package Manager (Git URLs of `https://github.com/nga-io/nga-sdk-unity` at tag `v0.1.0-rc.1`). See [Install](https://nga.io/docs/sdk/install/). - The candidate is built as 0.1.0: `getSdkVersion()` returns `0.1.0`, and only the coordinates and tags carry `-rc.1`. - Unity 2022.3: an Android release build needs *Minify > Release* on (Unity's default is off); Unity 6 needs nothing. **Libraries** - `nga-sdk`: initialization, consent and age, sessions, purchases from Google Play Billing 8+ and StoreKit, ad revenue from AppLovin MAX and Unity LevelPlay, and `logAdRevenue` for other networks. - `nga-sdk-render`: NGA's ads. **Platforms** - Android (API 23+), iOS (15.0+), and Unity (2022.3+) for Android and iOS builds. **Ads** - Native cross-promo: a banner at the bottom of the screen, 320 × 100 dp on a phone and 728 × 180 dp on a tablet, in your game's colors. You show it with `NGAAd.show` from that screen, the same way as a full-screen ad, and end it with `NGAAd.close()`. - Full-screen backfill: interstitial and rewarded, loaded and shown from your mediation's load-failed callback; examples for MAX, LevelPlay and AdMob. - The reward is decided on the device, with a typed denial. - `NGAImpression` for each impression through one app-wide listener. **Attribution** - Promoted installs measured by NGA, with the SDK in both games, and their day-1 and day-7 retention. - Your AppsFlyer or Adjust click and impression URLs, called by NGA's server on each tap and impression. **Testing** - Test devices registered in the portal, and the `DEBUG` init summary. - Games not on a store yet, promoted on your test devices only. **Privacy** - Typed consent, required at init; the IAB TCF, GPP and US Privacy keys read from your consent platform. - Child treatment from your audience and `setAge`. - No permission, prompt or usage string; on iOS, a privacy manifest in each framework, in native and Unity builds. **Not in this release:** see [Not in 0.1.0](https://nga.io/docs/sdk/#not-in-0-1-0).