exchange | Getting Started

This guide is for all app developers and publishers who wish to monetize the ad inventory on their iOS or Android apps using the light weight InMobi SDK. Before you begin integrating the SDK into your app, please follow the steps below to set up an account with InMobi, register your app and create ad placements:

Follow the simple steps and get started:

Along the way, we have highlighted important guidelines and best practices to ensure you have everything in place to monetize your app quick and easy without our assistance. Ensure that you pause for a moment to read through these messages.

Step 1: Signup with InMobi

Now that you’re here and InMobi is the chosen one, what are you waiting for? Let’s get started with your account right away. To set up an InMobi account:

  1. Sign up as a publisher.
  2. A verification email with a link will be sent to your registered email address. Click on the link to complete the verification process. (This address will be used for any future communication about your account).
  3. On log in, choose the applicability pertaining to GDPR.

Step 2: Register your App

Once you have created an account, you can proceed to register your app with InMobi. The following steps are only meant for apps published in an app store. If you have an app that is yet to be published, visit Step 2A. Let's proceed.

  1. Click Add an app

  2. Select your relevant Operating System
  3. Enter a valid app store URL
  4. Click Add to list additional apps you wish to monetize.
  5. View your completed profile from the drop down next to your user name.

Important: Please take a moment to read the compliance guidelines for properties directed to children below 13 years, and then select the check box if it applies to you.

Step 2A: Register an Unpublished App

If you have an unpublished app that is not live in the app store, just follow the simple steps below:

  1. Sign up as a Publisher.
  2. Complete the verification e-mail sent to the registered ID (The registered email ID here will receive all the communication).
  3. Choose the applicability pertaining to GDPR.
  4. Click Add app as shown in the dialog box.
  5. Choose operating system.
  6. When it's published, you can return to InMobi and link your app to its app store entry.

Remember: For apps without a URL, the test mode is enabled by default. Once live, you can click the link to enter the URL on the dashboard as shown below.

Step 3: Create Placements

  1. Select the relevant ad format to define the placement of your app.

  2. Scroll to your right/left to see more placements
  3. Enter details in Placement Name and click Create Placement
  4. Click Add Placement to create additional placements
  5. Once the setup is complete, you will get an overview of the placement details.

Important:
For Rewarded Video, please set the placement type to Interstitial.
For Native ad units, please ensure the right format and aspect ratio is selected.

Step 4: Update Payment Profile

Create, verify and activate your payment profile to make your earnings tangible! InMobi follows a payout cycle of 60 days. This means that your earnings for a given month will be credited to you at the end of the 60-day payout cycle. You have the option of receiving your payouts via PayPal or wire transfer/RTGS.

Note: This is a mandatory step and all publishers are requested to complete the details to monetize successfully.

  1. Select Earnings from the drop down next to your user name
  2. Select Add Account
  3. Add the following details:
    • Mode of Transfer
    • Bank Details
    • PAN Card Details
    • GST Details
  4. Once the setup is done, you will get an overview of your Payment Page.

Note: Your Payment Id is available under your account summary as shown below. You will be able to view it, after the payment details you provided are verified and approved.

Step 5: Control Ad Experience with Filters

By using the blocking controls built into InMobi, you can curate the experience shown to the user by reviewing and controlling the ads that appear in your app. InMobi supports ad filters at three levels to control the ad experience:

Level 1: Domain Filters

You can block ads from specific URLs. For example, you might not want to show your competitors' ads on your apps.


Level 2: URL or Keyword Filters

You can block ads by filtering URLs /Keyword Filters based on their ad text or landing page URL. For example, you can prevent ads containing the text 'weapons' or 'virus' from serving on your site or app.


Level 3: Category Filters

You can block ads from specific categories which will not be served on your app. The categories range from Business, Art, Finance, Fashion etc. For example, an app meant for kids has the option to block ads from specific categories.

Note: InMobi provides provision for blocking sensitive categories. You can block ads being served on content that includes topics such as politics, religion, mature content, gambling, etc.

Note: Blocking any ad will lower your potential earnings as it reduces competition for your inventory by removing advertiser bids from the auction. We recommend blocking only those ads that you feel are absolutely irrelevant and inappropriate to your content or your users.

exchange | InMobi Mediation (iOS)

Prerequisites

The following environments are required:

  • iOS9+
  • XCode11

Step 1: Integrating the SDK

  • Step 1.1: Download the InMobi SDK

    a. Download the latest InMobi SDK below. We also provide the option to use CocoaPods!

    Download the InMobi iOS SDK here.

    The SDK bundle contains all media adapters that we support. Prune the downloaded folder to retain the media adapters you need.


    b. CocoaPods (Optional)

    In the same directory as your YOUR_PROJECT.xcodeproj, create an empty file named Podfile and copy and paste the following:

              platform :ios, '9.0'
              target 'APP_NAME' do
                    pod 'inmobi-ios-sdk', :source => 'https://bitbucket.org/aerservllc/inmobi-ios-sdk-pod.git'
              end
    		

    Ensure your project has been closed. Using the terminal, navigate to the directory containing the Podfile and run the command: pod install. Once the installation finishes, use YOUR_PROJECT.xcworkspace to access your project moving forward.

    Inside the xcworkspace there should be a Pods directory included with a ios-sdk-pod sub-directory.

    Warning: Please remove all older versions of the InMobi SDK (8.X.X and older) and all older versions of the AerServ SDK. Otherwise, your code will not compile! Please reach out to your account manager if you have any questions. If you are using CocoaPods, be sure to remove the 'aerserv-ios-sdk' pod from your podfile and only use the 'inmobi-ios-sdk' pod.


  • Step 1.2: Add the Required Libraries

    Add the following frameworks into your project from the InMobi SDK download:

    • InMobiSDK.framework
    • network-support/AdColony/AdColony.framework
    • network-support/AdMob/GoogleMobileAds.framework
    • network-support/AppLovin/AppLovinSDK.framework
    • network-support/Chartboost/Chartboost.framework
    • network-support/Facebook/FBAudienceNetwork.framework
    • network-support/MillennialMedia/MMAdSDK.framework
    • network-support/MyTarget/MyTargetSDK.framework
    • network-support/RhythmOne/RYMMoatMobileAppKit.framework
    • network-support/RhythmOne/RhythmOneAds.framework
    • network-support/Tremor/TremorVideoAd.framework
    • network-support/Unity/UnityAds.framework
    • network-support/Vungle/VungleSDK.framework

    Add the following folders into your project from the InMobi SDK download:

    • network-support/Flurry/Flurry
    • network-support/Flurry/FlurryAds
    • network-support/MoPub/MoPubSDK

    Note: When using any mediation through the InMobi SDK, it is highly recommended that you use the framework that is provided along with the InMobi SDK download. These versions have been tested by our team and using any other version may not be officially supported.


  • Step 1.3: General Settings

    Under the Generaltab within your project's target, you'll need to add the follow settings:

    • Select all Device Orientation inside 'Deployment Info'.
    • Add the following dependencies toLinked Frameworks and Libraries:
      • AVFoundation.framework
      • AdSupport.framework
      • AudioToolbox.framework
      • CFNetwork.framework
      • CoreBluetooth.framework
      • CoreGraphic.framework
      • CoreGraphics.framework
      • CoreImage.framework
      • CoreLocation.framework
      • CoreMedia.framework
      • CoreMotion.framework
      • CoreTelephony.framework
      • CoreVideo.framework
      • EventKit.framework
      • EventKitUI.framework
      • FBAudienceNetwork.framework
      • Foundation.framework
      • GLKit.framework
      • MediaPlayer.framework
      • MessageUI.framework
      • OpenGLES.framework
      • QuartzCore.framework
      • SafariServices.framework
      • Security.framework
      • Social.framework
      • StoreKit.framework
      • SystemConfiguration
      • SystemConfiguration.framework
      • UIKit.framework
      • WebKit.framework
      • libc++.tbd
      • libxml2.2.tbd
      • libxml2.tbd
      • libz.1.2.5.tbd
      • libz.tbd

    One or more of the mediation adapters that you selected requiresthese frameworks. For the SDKs to work properly, you MUSTinclude these frameworks into your project.


  • Step 1.4: Create a bridging header (Swift Only)

    You will need to create a bridging header if your application is built with Swift. The bridging header exposes the Objective-C implementation to Swift. To create the bridging header, you'll need to do the following:

    1. Create a new header file, InMobiSDK-Bridging-Header.h.
    2. Add the following entry to the Bridging Header:
      #import <InMobiSDK/InMobiSDK.h>
      			
    3. Add the newly created header file's path to the target'sBuild Setting->Linking->Objective-C Bridging Header

  • Step 1.5: Build Settings

    Add the following flags to the target's Build Setting->Linking->Other Flag:

    • -ObjC
    • -fobjc-arc

  • Step 1.6: Info.plist

    You will need to add the following entries into your info.plist:

    <key>LSApplicationQueriesSchemes</key> <array> <string>fb</string>
    <string>instagram</string>
    <string>tumblr</string>
    <string>twitter</string> </array>
    <key>NSLocationWhenInUseUsageDescription</key>
    <string>Location is used to help target content to your general area</string>
    <key>NSCalendarsUsageDescription</key>
    <string>Some ad content may create a calendar event.</string>
    <key>NSPhotoLibraryUsageDescription</key>
    <string>Some ad content may require access to the photo library.</string>
    <key>NSCameraUsageDescription</key>
    <string>Some ad content may access camera to take picture.</string>
    <key>NSMotionUsageDescription</key>
    <string>Some ad content may require access to accelerometer for interactive ad experience.</string>
    		

    For iOS 9+, you will need to disable App Transport Security (ATS). Please refer here for more detail.

Step 2: Initializing the InMobi SDK

You must initialize our SDK before loading any ads.InitializingInMobi SDKwill update server-side configurations and additionally initialize any mediated ad sources.

Within the AerServ + InMobi dashboard, click on the inventory tab and edit the specific application that is being integrated. There will be an App ID associated to that application. Use that App ID to call InMobi SDK'sinitializeWithAppID:in the early phases of the application. Suggested place to kick off the initialization process is in the application's AppDelegateinside the application:didFinishLaunchingWithOptions:method.

You must initialize our SDK before loading any ads.It is recommended that you initialize the InMobi SDK as early as possible and 10 seconds before making your first ad request.

  • Objective-C
    /*!
     * Looks into the supplied app id and will run pre-initialization for any mediation partner sources that requires an extra setup phase.
     *
     * @param appId a string of the app id
     * @param userConsent a boolean flag for GDPR user consent. Set to YES if user consent was given and NO is user consent was denied
     */
    + (void)initializeWithAppID:(NSString*)appId andGDPRUserConsent:(BOOL)userConsent;
    /*!
     * Returns the GDPR user consent value.
     */
    + (BOOL)getGDPRConsentValue;
    /*!
     * Updates GDPR user consent. The updated GDPR user consent value will be used for all subsequent requests.
     * @param userConsent a boolean flag for GDPR user consent. Set to YES if user consent was given and NO is user consent was denied
     */
    + (void)setGDPRWithUserConsent:(BOOL)userConsent;
    		
  • Swift
        /*!
         * Looks into the supplied app id and will run pre-initialization for any mediation partner sources that requires an extra setup phase.
         *
         * @param appId a string of the app id
         */
        class func initialize(withAppID appId: String?) { }
        /*!
         * Looks into the supplied app id and will run pre-initialization for any mediation partner sources that requires an extra setup phase.
         *
         * @param appId a string of the app id
         * @param userConsent a boolean flag for GDPR user consent. Set to YES if user consent was given and NO is user consent was denied
         */
        class func initialize(withAppID appId: String?, andGDPRUserConsent userConsent: Bool) { }
        /*!
         * Returns the GDPR user consent value.
         */
        class func getGDPRConsentValue() -> Bool { }
        /*!
         * Updates GDPR user consent. The updated GDPR user consent value will be used for all subsequent requests.
         * @param userConsent a boolean flag for GDPR user consent. Set to YES if user consent was given and NO is user consent was denied
         */
        class func setGDPRWithUserConsent(_ userConsent: Bool) { }
    		

How to obtain the app ID:

  • Log in to the AerServ + InMobi platform.
  • Go to the 'Inventory' tab in the top navigation bar.
  • Click the 'Edit' icon next to the app whose ID you wish to obtain.
  • You will find the app ID at the very top of the page.

To set or update the General Data Protection Regulation (GDPR) user consent flag, call InMobi SDK’s +setGDPRWithUserConsent: method. Pass YES/true for user consent if GDPR user consent was granted and NO/false if user consent was denied or if unknown.
To have the GDPR user consent flag to be set before an ad request, call +setGDPRWithUserConsent: before calling -loadAd. The values passed into +setGDPRWithUserConsent: will be stored in the NSUserDefaults, persisting the chosen consent. Thus, it is not necessary to reset the user consent value prior to each ad request; the value set is applicable for all subsequent requests until that value is reset.

An example would be:

  • Objective-C
    [AerServSDK initializeWithAppID:@"APP_ID" andGDPRUserConsent:YES];
    // or
    [AerServSDK setGDPRWithUserConsent:YES];
    [AerServSDK initializeWithAppID:@"APP_ID];
    // to view current consent:
    [AerServSDK getGDPRConsentValue];
    		
  • Swift
    AerServSDK.initialize(withAppID: "APP_ID", andGDPRUserConsent: true)
    // or
    AerServSDK.setGDPRWithUserConsent(true)
    AerServSDK.initialize(withAppID: "APP_ID")
    // to view current consent:
    AerServSDK.getGDPRConsentValue()
    		

Mediation Disclaimer: Please be advised that although we are GDPR compliant, we currently have no way to send GDPR compliance as well as user consent to our mediated SDK partners. Compliance responsibility and request handling will solely depend on the SDK mediated partner. Please contact your mediated partners to avoid any issues and/or complications.

Step 3: Displaying Banner Ads

  • Step 3.1: Loading and Showing Banners

    • Create anASAdViewobject by passing in a placement setup on the AerServ + InMobi dashboard as well as the banner's size. Refer to ASAdView.hforInMobi SDK'spredefined sizes.
      • Objective-C
        #import <InMobiSDK/InMobiSDK.h>
        @interface ViewController()
        @property(nonatomic, strong) ASAdView* asAdView;
        @end
        @implementation ViewController
        - (void)loadBannerAd {
          // Create the AerServ banner object
          self.asAdView = [ASAdView viewWithPlacementID:@"1024876" andAdSize:ASBannerSize];   
        }
        @end
        				
      • Swift
        class ViewController: UIViewController, {
          var asAdView: ASAdView?
          func loadBannerAd() {
            // Create the AerServ banner object
            asAdView? = ASAdView(placementID: "1024876", andAdSize: ASBannerSize)
          }
        }
        				

    • Add theASAdViewobject to your application's view.
      • Objective-C
        #import <InMobiSDK/InMobiSDK.h>
        @interface ViewController()
        @property(nonatomic, strong) ASAdView* asAdView;
        @end
        @implementation ViewController
        - (void)loadBannerAd {
          // Create the AerServ banner object
          self.asAdview = [ASAdView viewWithPlacementID:@"1024876" andAdSize:ASBannerSize];
          // Add banner to a parent view
          [self.view addSubview:asAdView];
        }
        @end
        				
      • Swift
        class ViewController: UIViewController {
          var asAdView: ASAdView?
          func loadBannerAd() {
            // Create the AerServ banner object
            asAdView? = ASAdView(placementID: "1024876", andAdSize: ASBannerSize)
            // Add banner to a parent view
            view.addSubview(asAdView!)
          }
        }
        				
    • In the view controller that the ASAdView object is added to, make sure that the view controller adheres to the ASAdViewDelegate protocol. Additionally, add the callback -viewControllerForPresentingModalView that will return itself.
      • Objective-C
        #import <InMobiSDK/InMobiSDK.h>
        @interface ViewController() <ASAdViewDelegate>
        @property(nonatomic, strong) ASAdView* asAdView;
        @end
        @implementation ViewController
        - (void)loadBannerAd {
          // Create the AerServ banner object
          self.asAdview = [ASAdView viewWithPlacementID:@"1024876" andAdSize:ASBannerSize];
          self.asAdview.delegate = self;
          // Add banner to a parent view
          [self.view addSubview:asAdView];
        }
        #pragma mark - AerServ Interstitial Callbacks 
        - (UIViewController*)viewControllerForPresentingModalView {
          return self;
        }
        @end
        				
      • Swift
        class ViewController: UIViewController, ASAdViewDelegate {
          var asAdView: ASAdView?
          func loadBannerAd() {
            // Create the AerServ banner object
            asAdView? = ASAdView(placementID: "1024876", andAdSize: ASBannerSize)
            asAdView?.delegate = self
            // Add banner to a parent view
            view.addSubview(asAdView!)
          }
          //MARK: AerServ Banner Callback
          func viewControllerForPresentingModalView() -> UIViewController! {
            return self  
          }
        }
        				
    • Lastly, kick off the ad request by loading the ad.
      • Objective-C
        #import <InMobiSDK/InMobiSDK.h>
        @interface ViewController() <ASAdViewDelegate>
        @property(nonatomic, strong) ASAdView* asAdView;
        @end
        @implementation ViewController
        - (void)loadBannerAd {
          // Create the AerServ banner object
          self.asAdview = [ASAdView viewWithPlacementID:@"1024876" andAdSize:ASBannerSize];
          self.asAdview.delegate = self;
          // Add banner to a parent view
          [self.view addSubview:asAdView];
          // Use loadAd to make a request to the AerServ ad server for a ad
          [self.asAdView loadAd];
        }
        #pragma mark - AerServ Banner Callbacks
        - (UIViewController*)viewControllerForPresentingModalView {
          return self;
        }
        @end
        				
      • Swift
        class ViewController: UIViewController, ASAdViewDelegate {
          var asAdView: ASAdView?
          func loadBannerAd() {
            // Create the AerServ banner object
            asAdView? = ASAdView(placementID: "1024876", andAdSize: ASBannerSize)
            asAdView?.delegate = self
            // Add banner to a parent view
            view.addSubview(asAdView!)
            // Use loadAd to make a request to the AerServ ad server for a ad
            asAdView?.loadAd()
          }
          //MARK: AerServ Banner Callback
          func viewControllerForPresentingModalView() -> UIViewController! {
            return self  
          }
        }
        				

  • Step 3.2:Optional Banner Callbacks

    You can additionally assign a delegate to listen for the banner's callback events. A few of the callbacks that can be listened to are:

    • Objective-C
      #pragma mark - AerServ Banner Callbacks
      - (void)adViewDidLoadAd:(ASAdView*)adView { }
      - (void)adViewDidPreloadAd:(ASAdView*)adView { }
      - (void)adViewDidFailToLoadAd:(ASAdView*)adView withError:(NSError*)error { }
      - (void)adWasClicked:(ASAdView*)adView { }
      			
    • Swift
      //MARK: AerServ Banner Callbacks
      func adViewDidLoadAd(_ adView: ASAdView!) { }
      func adViewDidPreloadAd(_  adView: ASAdView!) { }
      func adViewDidFail(toLoadAd adView: ASAdView!, withError error: Error!) { }
      func adWasClicked(_ adView: ASAdView!) { }
      			

    Please refer to ASAdView.hfor all available callbacks and descriptions of each. Settings for specifying the banner refresh time interval, preloading, and more can be found in the ASAdViewheader as well.

Step 4: Displaying Interstitial Ads

  • Step 4.1: Loading and Displaying Interstitials

    • Create anASInterstitialViewControllerobject with a placement setup on the AerServ + InMobi dashboard and a delegate that conforms to ASInterstitialViewControllerDelegate.
      • Objective-C
        #import <InMobiSDK/InMobiSDK.h>
        @interface ViewController() <ASInterstitialViewControllerDelegate>
        @property(nonatomic, strong) ASInterstitialViewController* asInterstitialVC;
        @end
        @implementation ViewController
        - (void)loadInterstitialAd {
          // Create the AerServ interstitial object
          self.asInterstitialVC = [ASInterstitialViewController viewControllerForPlacementID:@"1000741" withDelegate:self];
        }
        @end
        				
      • Swift
        import AerServSDK
        class ViewController: UIViewController, ASInterstitialViewControllerDelegate {
          var asInterstitialVC: ASInterstitialViewController?
          func loadInterstitialAd() {
            // Create the AerServ interstitial object
            asInterstitialVC? = ASInterstitialViewController(forPlacementID: "1000741", with: self)
          }
        }
        				

    • Start the ad request by loading an ad with your specified settings.
      • Objective-C
        #import <InMobiSDK/InMobiSDK.h>
        @interface ViewController() <ASInterstitialViewControllerDelegate>
        @property(nonatomic, strong) ASInterstitialViewController* asInterstitialVC;
        @end
        @implementation ViewController
        - (void)loadInterstitialAd {
          // Create the AerServ interstitial object
          self.asInterstitialVC = [ASInterstitialViewController viewControllerForPlacementID:@"1000741" withDelegate:self];
          // Use loadAd to make a request to the AerServ ad server for a ad
          [self.asInterstitialVC loadAd];
        }
        @end
        				
      • Swift
        class ViewController: UIViewController, ASInterstitialViewControllerDelegate {
          var interstitial: ASInterstitialViewController?
          func loadInterstitialAd() {
            // Create the AerServ interstitial object
            asInterstitialVC? = ASInterstitialViewController(forPlacementID: "1000741", with: self)
            // Use loadAd to make a request to the AerServ ad server for a ad
            asInterstitialVC?.loadAd()
          }
        }
        				
    • When the ad is ready, a callback event will be triggered. From the callback, the interstitial ad can be shown from a parent view controller.
      • Objective-C
        #import <InMobiSDK/InMobiSDK.h>
        @interface ViewController() <ASInterstitialViewControllerDelegate>
        @property(nonatomic, strong) ASInterstitialViewController* asInterstitialVC;
        @end
        @implementation ViewController
        - (void)loadInterstitialAd {
          // Create the AerServ interstitial object
          self.asInterstitialVC = [ASInterstitialViewController viewControllerForPlacementID:@"1000741" withDelegate:self];
          // Use loadAd to make a request to the AerServ ad server for a ad
          [self.asInterstitialVC loadAd];
        }
        #pragma mark - AerServ Interstitial Callbacks
        - (void)interstitialViewControllerAdLoadedSuccessfully:(ASInterstitialViewController*)viewController {
          [viewController showFromViewController:self];
        }
        @end
        				
      • Swift
        class ViewController: UIViewController, ASInterstitialViewControllerDelegate {
          var asInterstitialVC: ASInterstitialViewController?
          func loadInterstitialAd() {
            // Create the AerServ interstitial object
            asInterstitialVC? = ASInterstitialViewController(forPlacementID: "1000741", with: self)
            // Use loadAd to make a request to the AerServ ad server for a ad
            asInterstitialVC?.loadAd()
          }
          //MARK: AerServ Interstitial Callbacks
          func interstitialViewControllerAdLoadedSuccessfully(_ viewController: ASInterstitialViewController!) {
            asInterstitialVC?.show(from: self)
          } 
        }
        				

  • Step 4.2: Optional Interstitial Steps

    Preloading Interstitial Ads

    Preloading an ad works in a similar fashion. Before loading the ad, the isPreloadflag should be set to YES. Another callback event can be listened to for notification that a preloaded ad is ready to be shown.

    • Objective-C
      #import <InMobiSDK/InMobiSDK.h>
      @interface ViewController() <ASInterstitialViewControllerDelegate>
      @property(nonatomic, strong) ASInterstitialViewController* asInterstitialVC;
      @property(nonatomic, assign) BOOL didPreload;
      @end
      @implementation ViewController
      /**
       * We check if the preload flag has been previously set. This is so that we don't waste a ad that has already been preloaded
       * and calling another load won't necessary fill.
       */
      - (void)loadAd {
        if(!self.didPreload) {
          self.asInterstitialVC = [ASInterstitialViewController viewControllerForPlacementID:@"1000741" withDelegate:self];
          self.asInterstitialVC.isPreload = YES;
          [self.asInterstitialVC loadAd];
        } else {
          NSLog(@"--- Ad is already loaded ---");
        }
      }
      - (void)showAd {
        if(!self.didPreload) {
          [self.asInterstitialVC showFromViewController:aViewController];
        } else {
          NSLog(@"--- Interstitial hasn't preloaded ---");
        }
      }
      #pragma mark - AerServ Interstitial Callbacks
      - (void)interstitialViewControllerDidPreloadAd:(ASInterstitialViewController*)viewController {
        NSLog(@"--- Interstitial View Controller Did Preload Ad ---");
        self.didPreload = YES;
        // - [self.asInterstitialVC showFromViewController] can be called anything after this point.
      }
      - (void)interstitialViewControllerAdFailedToLoad:(ASInterstitialViewController*)viewController withError:(NSError*)error {
        NSLog(@"--- Interstitial ad failed: ', error, ' ---");
        self.didPreload = NO;
      }
      - (void)interstitialViewControllerDidDisappear:(ASInterstitialViewController*)viewController {
        NSLog(@"--- Interstitial ad did disappear ---");
        self.didPreload = NO;
      }
      @end
      			
    • Swift
      class ViewController: UIViewController, ASInterstitialViewControllerDelegate {
        var asInterstitialVC: ASInterstitialViewController?
        var didPreload = false
        /**
         * We check if the preload flag has been previously set. This is so that we don't waste a ad that has already been preloaded
         * and calling another load won't necessary fill.
         */
        func loadAd() {
          if(!didPreload) {
            asInterstitialVC? = ASInterstitialViewController(forPlacementID: "1000741", with: self)
            asInterstitialVC?.isPreload = true
            asInterstitialVC?.loadAd()
          }
        }
        func showAd() {
          if(didPreload) {
            asInterstitialVC?.show(from: aViewController)
          } else {
            print("--- Interstitial hasn't preloaded ---")
          }
        }
        //MARK: AerServ Interstitial Callbacks
        func interstitialViewControllerDidPreloadAd(_ viewController: ASInterstitialViewController!) {
          print("---- Interstitial ViewController Did Preload Ad ---")
          didPreload = true
          // interstitial?.show(from: self) can be called anything after this point.
        }
        func interstitialViewControllerAdFailed(toLoad viewController: ASInterstitialViewController!, withError error: Error!) {
          print("--- Interstitial ad failed: ", error, " ---")
          didPreload = false;
        }
        func interstitialViewControllerDidDisappear(_ viewController: ASInterstitialViewController!) {
          print("--- Interstitial ad did disappear ---")
          didPreload = false;
        }
      }
      			
    Additional Interstitial Callbacks

    Other callback events that can be listened to are:

    • Objective-C
      #pragma mark - AerServ Interstitial Callbacks
      - (void)interstitialViewControllerWillAppear:(ASInterstitialViewController*)viewController { }
      - (void)interstitialViewControllerDidAppear:(ASInterstitialViewController*)viewController { }
      - (void)interstitialViewControllerWillDisappear:(ASInterstitialViewController*)viewController { }
      - (void)interstitialViewControllerDidDisappear:(ASInterstitialViewController*)viewController { }
      - (void)interstitialViewControllerAdWasTouched:(ASInterstitialViewController*)viewController { }
      - (void)interstitialViewControllerAdFailedToLoad:(ASInterstitialViewController*)viewController withError:(NSError*)error { }
      			
    • Swift
      //MARK: AerServ Interstitial Callbacks
      func interstitialViewControllerWillAppear(_ viewController: ASInterstitialViewController!) { }
      func interstitialViewControllerDidAppear(_ viewController: ASInterstitialViewController!) { }
      func interstitialViewControllerWillDisappear(_ viewController: ASInterstitialViewController!) { }
      func interstitialViewControllerDidDisappear(_ viewController: ASInterstitialViewController!) { }
      func interstitialViewControllerAdWasTouched(_ viewController: ASInterstitialViewController!) { }
      func interstitialViewControllerAdFailed(toLoad viewController: ASInterstitialViewController!, withError error: Error!) { }
      			

    Please refer to ASInterstitialViewController.hfor all available callbacks and descriptions for each. Settings for supplying video player controls, and more can be found in the ASInterstitialViewControllerheader as well.

Step 5: Additional Settings

Header Bidding Requests

The Header Bidding flag is now enabled by default, and "useHeaderBidding" has been deprecated and is no longer needed.

Pausing & Resuming Video Ads(not supported in InMobi SDK 8.0.1 & 8.0.2)

Both banners and interstitials have the ability to pause and resume play of VAST video ads.

  • Objective-C
    #import <InMobiSDK/InMobiSDK.h>
    @interface ViewController() <ASAdViewDelegate>
    @property(nonatomic, strong) ASAdView* asAdView;
    @end
    @implementation ViewController
    - (void)loadBannerAd() {
      self.asAdView = [ASAdView viewWithPlacementID:@"1024876" andAdSize:ASBannerSize];
      self.asAdView.delegate = self;
      [self.view addSubview:self.asAdView];
      [self.asAdView loadAd];
    }
    /**
     * You may want to pause the video when the banner goes off of the screen.
     */
    - (void)pauseVideo {
      [self.asAdView pause];
    }
    /**
     * Once the banner comes back on screen, you can resume the video
     */
    - (void)resumeVideo {
      [self.asAdView play];
    }
    #pragma mark - AerServ Banner Callbacks
    - (UIViewController*)viewControllerForPresentingModalView {
      return self;
    }
    @end
    		
  • Swift
    class ViewController: UIViewController,  ASAdViewDelegate {
      var asAdView: ASAdView?
      func loadBannerAd() {
        asAdView? = ASAdView(placementID: "1024876" andAdSize: ASBannerSize)
        asAdView?.delegate = self
        view.addSubview(asAdView!)
        asAdView?.loadAd()
      }
      /**
       * You may want to pause the video when the banner goes off of the screen.
       */
      func pauseVideo {
        asAdView?.pause()
      }
      /**
       * Once the banner comes back on screen, you can resume the video
       */
      func resumeVideo {
        asAdView?.play()
      }
      //MARK: AerServ Banner Callbacks
      func viewControllerForPresentingModalView() -> UIViewController! {
        return self  
      }
    }
    		
  • Virtual Currency

    Once you have setup your placement with virtual currency, there are two additional callbacks that conform to the protocol ASInterstitialViewControllerDelegate. The first callback will notify that the virtual currency data has loaded.

    • Objective-C
      #import <InMobiSDK/InMobiSDK.h>
      @interface ViewController() <ASInterstitialViewControllerDelegate>
      @property(nonatomic, strong) ASInterstitialViewController* asInterstitialVC;
      @end
      @implementation ViewController
      - (void)loadInterstitialAd {
        self.asInterstitialVC = [ASInterstitialViewController viewControllerForPlacementID:@"1000741" withDelegate:self];
        [self.asInterstitialVC loadAd];
      }
      #pragma mark - AerServ Interstitial Callbacks
      - (void)interstitialViewControllerAdLoadedSuccessfully:(ASInterstitialViewController*)viewController {
        [viewController showFromViewController:self];
      }
      /**
       * The first callback will notify when we load the creative. Note that you can also get the buyerName and buyer price throught the didLoadAdWithTransactionInfo and
       * didShowAdWithTransactionInfo.
       */
      - (void)interstitialViewControllerDidVirtualCurrencyLoad:(ASInterstitialViewController*)viewController vcData:(NSDictionary*)vcData {
        NSString* name = vcData[@"name"];
        NSNumber* rewardAmount = vcData[@"rewardAmount"];
        NSString* buyerName = vcData[@"buyerName"];
        NSNumber* buyerPrice = vcData[@"buyerPrice"];
        // Add your logic here  
      }
      /** 
       * The second callback will notify when the virtual currency has been rewarded. This will only fire after the user has watch 100% of the video on a virtual currency
       * enable placement.
       */
      - (void)interstitialViewControllerDidVirtualCurrencyReward:(ASInterstitialViewController*)viewController vcData:(NSDictionary*)vcData {
        NSString* name = vcData[@"name"];
        NSNumber* rewardAmount = vcData[@"rewardAmount"];
        // Add your logic here  
      }
      @end
      		
    • Swift
      class ViewController: UIViewController, ASInterstitialViewControllerDelegate {
        var asInterstitialVC: ASInterstitialViewController?
        func loadInterstitialAd() {
          asInterstitialVC? = ASInterstitialViewController(forPlacementID: "1000741", with: self)
          asInterstitialVC?.loadAd()
        }
        //MARK: AerServ Interstitial Callback
        func interstitialViewControllerAdLoadedSuccessfully(_ viewController: ASInterstitialViewController!) {
          asInterstitialVC?.show(from: self)
        }
        /**
         * The first callback will notify when we load the creative. 
         */
        func interstitialViewControllerDidVirtualCurrencyLoad(_ viewController: ASInterstitialViewController!, vcData: [AnyHashable : Any]!) {
          let name: String = vcData?["name"] as! String
          let amount: NSNumber = vcData?["rewardAmount"] as! NSNumber
          let buyerName: String = vcData?["buyerName"] as! String
          let buyerPrice: NSNumber = vcData?["buyerName"] as! NSNumber
          // Add your logic here  
        }
        /**
         * The second callback will notify when the virtual currency has been rewarded. This will only fire after the user has watch 100% of the video on a virtual currency 
         * enable placement.
         */
        func interstitialViewControllerDidVirtualCurrencyReward(_ viewController: ASInterstitialViewController!, vcData: [AnyHashable : Any]!) {
          let name: String = vcData?["name"] as! String
          let amount: NSNumber = vcData?["rewardAmount"] as! NSNumber
          // Add your logic here  
        }
      }
      		

    For both of these callbacks, there is a vcData dictionary object attached that will contain the keys "name" and "rewardAmount".

  • Ad Transaction Information

    During the process of showing an ad, the InMobi SDK will additionally return information pertaining to the buyer for your ad space and the price that the ad space was bought for. This detailed information can be found from these callbacks:

    • Objective-C
      #import <InMobiSDK/InMobiSDK.h>
      @interface ViewController() <ASInterstitialViewControllerDelegate, ASAdViewDelegate>
      @property(nonatomic, strong) ASInterstitialViewController* asInterstitialVC;
      @property(nonatomic, strong) ASAdView* asAdView;
      @end
      @implementation ViewController 
      /**
       * When gettings the ad transaction information, no change are needed in how we load the ASInterstitialViewController. We
       * just need to add in the callback.
       */
      - (void)loadInterstitialAd {
        self.asInterstitialVC = [ASInterstitialViewController viewControllerForPlacementID:@"1000741" withDelegate:self];
        [self.asInterstitialVC loadAd];
      }
      /**
       * When gettings the ad transaction information, no change are needed in how we load the ASAdView. We
       * just need to add in the callback.
       */
      - (void)loadBannerAd {
        self.asAdView = [ASAdView viewWithPlacementID:@"1024876" andAdSize:ASBannerSize];
        self.asAdView.delegate = self;
        [self.view addSubview:self.asAdView];
        [self.asAdView loadAd];
      }
      #pragma mark - AerServ Interstitial Callbacks
      - (void)interstitialViewControllerAdLoadedSuccessfully:(ASInterstitialViewController*)viewController {
        [viewController showFromViewController:self];
      }
      /**
       * The didLoadAdWithTransactionInfo callback will contain the transaction information of the ad from the first load attempt. The transaction 
       * information from this callback may be different from the ad the produce the impression.
       */
      - (void)interstitialAdManager:(ASInterstitialAdManager*)viewController didLoadAdWithTransactionInfo:(NSDictionary*)transactionInfo {
        NSString* buyerName = transcationData[@"buyerName"];
        NSNumber* buyerPrice = transcationData[@"buyerPrice"];
        // Add your logic here  
      }
      /**
       * The didShowAdWithTransactionInfo callback will cotanin the transaction information of the ad that produced a impression.  
       */
      - (void)interstitialViewController:(ASInterstitialViewController*)viewController didShowAdWithTransactionInfo:(NSDictionary*)transcationData {
        NSString* buyerName = transcationData[@"buyerName"];
        NSNumber* buyerPrice = transcationData[@"buyerPrice"];
        // Add your logic here  
      }
      #pragma mark - AerServ Banner Callbacks
      - (UIViewController*)viewControllerForPresentingModalView {
        return self;
      }
      /**
       * The didLoadAdWithTransactionInfo callback will contain the transaction information of the ad from the first load attempt. The transaction 
       * information from this callback may be different from the ad the produce the impression.
       */
      - (void)adView:(ASAdView*)adVidew didLoadAdWithTransactionInfo:(NSDictionary*)transcationData {
        NSString* buyerName = transcationData[@"buyerName"];
        NSNumber* buyerPrice = transcationData[@"buyerPrice"];
        // Add your logic here  
      }
      /**
       * The didShowAdWithTransactionInfo callback will cotanin the transaction information of the ad that produced a impression.  
       */
      - (void)adView:(ASAdView*)adVidew didShowAdWithTransactionInfo:(NSDictionary*)transcationData {
        NSString* buyerName = transcationData[@"buyerName"];
        NSNumber* buyerPrice = transcationData[@"buyerPrice"];
        // Add your logic here
      }
      @end
      		
    • Swift
      class ViewController: UIViewController, ASInterstitialViewControllerDelegate, ASAdViewDelegate {
        var asInterstitialVC: ASInterstitialViewController?
        var asAdView: ASAdView?
        /**
         * When gettings the ad transaction information, no change are needed in how we load the ASInterstitialViewController. We
         * just need to add in the callback.
         */
        func loadInterstitialAd() {
          asInterstitialVC? = ASInterstitialViewController(forPlacementID: "1000741", with: self)
          asInterstitialVC?.loadAd()
        }
        /**
         * When gettings the ad transaction information, no change are needed in how we load the ASAdView. We
         * just need to add in the callback.
         */
        func loadBannerAd() {
          asAdView? = ASAdView(placementID: "1024876" andAdSize: ASBannerSize)
          asAdView?.delegate = self
          view.addSubview(asAdView!)
          asAdView?.loadAd()
        }
        //MARK: AerServ Interstitial Callbacks
        func interstitialViewControllerAdLoadedSuccessfully(_ viewController: ASInterstitialViewController!) {
          asInterstitialVC?.show(from: self)
        }
        /**
         * The didLoadAdWithTransactionInfo callback will contain the transaction information of the ad from the first load attempt. The transaction 
         * information from this callback may be different from the ad the produce the impression.
         */
        func interstitialViewController(_ viewController: ASInterstitialViewController!, didLoadAdWithTransactionInfo transcationData: [AnyHashable : Any]!) {
          let buyerName:String = transcationData?["buyerName"] as! String;
          let buyerPrice:NSNumber = transcationData?["buyerName"] as! NSNumber;
          // Add your logic here
        }
        /**
         * The didShowAdWithTransactionInfo callback will cotanin the transaction information of the ad that produced a impression.  
         */
        func interstitialViewController(_ viewController: ASInterstitialViewController!, didShowAdWithTransactionInfo transcationData: [AnyHashable : Any]!) {
          let buyerName:String = transcationData?["buyerName"] as! String;
          let buyerPrice:NSNumber = transcationData?["buyerName"] as! NSNumber;
          // Add your logic here
        }
        //MARK: Aerserv Banner Callback
        func viewControllerForPresentingModalView() -> UIViewController! {
          return self  
        }
        /**
         * The didLoadAdWithTransactionInfo callback will contain the transaction information of the ad from the first load attempt. The transaction 
         * information from this callback may be different from the ad the produce the impression.
         */ 
        func adView(_ adView: ASAdView!, didLoadAdWithTransactionInfo transcationData: [AnyHashable : Any]!) { 
          let buyerName:String = transcationData?["buyerName"] as! String;
          let buyerPrice:NSNumber = transcationData?["buyerName"] as! NSNumber;
          // Add your logic here
        }
        /**
         * The didShowAdWithTransactionInfo callback will cotanin the transaction information of the ad that produced a impression.  
         */
        func adView(_ adView: ASAdView!, didShowAdWithTransactionInfo transcationData: [AnyHashable : Any]!) { 
          let buyerName:String = transcationData?["buyerName"] as! String;
          let buyerPrice:NSNumber = transcationData?["buyerName"] as! NSNumber;
          // Add your logic here
        }
      }
      		

    The transactionData dictionary object contains keys for "buyerName" and "buyerPrice" that can be accessed for the transaction information values.

    Adding Publisher Keys

    Custom revenue reports can be generated via the SDK by assigning a dictionary object with publisher key value pairs to the pubKeys property. This is available for both interstitials and banners. For details about publisher keys, click here.

    • Objective-C
      #import <InMobiSDK/InMobiSDK.h>
      @interface ViewController() <ASInterstitialViewControllerDelegate, ASAdViewDelegate>
      @property(nonatomic, strong) ASInterstitialViewController* asInterstitialVC;
      @property(nonatomic, strong) ASAdView* asAdView;
      @end
      @implementation ViewController
      /**
       * Before loading a ad with ASInterstitialViewController, you'll need to set the values for pubKeys.
       */
      - (void)loadInterstitialAd {
        self.asInterstitialVC = [ASInterstitialViewController viewControllerForPlacementID:@"1000741" withDelegate:self];
        self.asInterstitialVC.pubKeys = @{@"channel_category":@"music", @"content_rating":@"4 stars"}; // Dictionary containing publisher keys
        [self.asInterstitialVC loadAd];
      }
      /**
       * Before loading a ad with ASAdView, you'll need to set the values for pubKeys.
       */
      - (void)loadBannerAd() {
        self.asAdView = [ASAdView viewWithPlacementID:@"1024876" andAdSize:ASBannerSize];
        self.asAdView.delegate = self;
        self.asAdView.pubKeys = @{@"partner_name":@"bloomberg", @"episode_id":@"77889"}; // Dictionary containing publisher keys
        [self.view addSubview:self.asAdView];
        [self.asAdView loadAd];
      }
      #pragma mark - AerServ Interstitial Callbacks
      - (void)interstitialViewControllerAdLoadedSuccessfully:(ASInterstitialViewController*)viewController {
        [viewController showFromViewController:self];
      }
      #pragma mark - AerServ Banner Callbacks
      - (UIViewController*)viewControllerForPresentingModalView {
        return self;
      }
      @end
      		
    • Swift
      class ViewController: UIViewController, ASInterstitialViewControllerDelegate, ASAdViewDelegate {
        var asInterstitialVC: ASInterstitialViewController?
        var asAdView: ASAdView?
        /**
         * Before loading a ad with ASInterstitialViewController, you'll need to set the values for pubKeys.
         */
        func loadInterstitialAd() {
          asInterstitialVC? = ASInterstitialViewController(forPlacementID: "1000741", with: self)
          asInterstitialVC?.pubKeys = ["channel_category": "music", "content_rating": "4 stars"] // Dictionary containing publisher keys
          asInterstitialVC?.loadAd()
        }
        /**
         * Before loading a ad with ASAdView, you'll need to set the values for pubKeys.
         */
        func loadBannerAd() {
          asAdView? = ASAdView(placementID: "1024876" andAdSize: ASBannerSize)
          asAdView?.delegate = self
          asAdView?.pubKeys = ["partner_name": "bloomberg", "episode_id": "77889"] // Dictionary containing publisher keys.
          view.addSubview(asAdView!)
          asAdView?.loadAd()
        }
        //MARK: AerServ Interstitial Callbacks
        func interstitialViewControllerAdLoadedSuccessfully(_ viewController: ASInterstitialViewController!) {
          asInterstitialVC?.show(from: self)
        }
        //MARK: AerServ Banner Callbacks
        func viewControllerForPresentingModalView() -> UIViewController! {
          return self  
        }
      }
      		

    Note: Publisher Keys can also be used as custom macro on the SSUI. Please contact support on instructions on how to use this feature.

  • Enabling Geolocation Targeting

    If your application already requests permission for geolocation, skip this step. Enabling geolocation will help target ads relevant to your user's physical location. This can be done by adding key-value pairs to your application's Info.plist. The keys will be:

    • NSLocationAlwaysUsageDescription
    • NSLocationWhenInUseUsageDescription

    The value for both will be a string that will be displayed when your application is requesting for geolocation permission.

    <key>NSLocationAlwaysUsageDescription</key> 
    <string>Location is used to help target content to your general area</string>
    <key>NSLocationWhenInUseUsageDescription</key> 
    <string>Location is used to help target content to your general area</string>
    	

  • Disabling App Transport Security for iOS 9+

    Select your application's Info.plist, right-click on it and open as source code. Copy the following code into your Info.plist'sxml.

    <key>NSAppTransportSecurity</key>
    <dict>
      <key>NSAllowsArbitraryLoads</key><true/>
    </dict>
    	

  • Muting Interstitial Ads(not supported in InMobi SDK 8.0.1 & 8.0.2)

    Video ads can be muted programmatically. This setting will not affect SDK mediation.

    • Objective-C
      #import <InMobiSDK/InMobiSDK.h>
      @interface ViewController() <ASInterstitialViewControllerDelegate, ASAdViewDelegate>
      @property(nonatomic, strong) ASInterstitialViewController* asInterstitialVC;
      @property(nonatomic, strong) ASAdView* asAdView;
      @end
      @implementation ViewController
      /**
       * Before loading a ad with ASInterstitialViewController, you'll need to set the mute flag. This function will
       * not work with any SDK mediation.
       */
      - (void)loadInterstitialAd {
        self.asInterstitialVC = [ASInterstitialViewController viewControllerForPlacementID:@"1000741" withDelegate:self];
        self.asInterstitialVC.isMuted = YES; // The flag to toggle mutability.
        [self.asInterstitialVC loadAd];
      }
      /**
       * Before loading a ad with ASAdView, you'll need to set the mute flag. This function will not work with any SDK mediation.
       */
      - (void)loadBannerAd {
        self.asAdView = [ASAdView viewWithPlacementID:@"1024876" andAdSize:ASBannerSize];
        self.asAdView.delegate = self;
        self.asAdView.isMuted = YES; // The flag to toggle mutability.
        [self.view addSubview:self.asAdView];
        [self.asAdView loadAd];
      }
      #pragma mark - Aerserv Interstitial Callback
      - (void)interstitialViewControllerAdLoadedSuccessfully:(ASInterstitialViewController*)viewController {
        [viewController showFromViewController:self];
      }
      #pragma mark - AerServ Banner Callback
      - (UIViewController*)viewControllerForPresentingModalView {
        return self;
      }
      @end
      		
    • Swift
      class ViewController: UIViewController, ASInterstitialViewControllerDelegate, ASAdViewDelegate {
        var asInterstitialVC: ASInterstitialViewController?
        var asAdView: ASAdView?
        /**
         * Before loading a ad with ASInterstitialViewController, you'll need to set the mute flag.
         * This function will not work with any SDK mediation.
         */
        func loadInterstitialAd() {
          asInterstitialVC? = ASInterstitialViewController(forPlacementID: "1000741", with: self)
          asInterstitialVC?.isMuted = true // The flag to toggle mutability.
          asInterstitialVC?.loadAd()
        }
        /**
         * Before loading a ad with ASAdView, you'll need to set the mute flag. This function will not work
         * with any SDK mediation.
         */
        func loadBannerAd() {
          asAdView? = ASAdView(placementID: "1024876" andAdSize: ASBannerSize)
          asAdView?.delegate = self
          asAdView?.isMuted = true // The flag to toggle mutability.
          view.addSubview(banner!)
          asAdView?.loadAd()
        }
        //MARK: AerServ Interstitial Callbacks
        func interstitialViewControllerAdLoadedSuccessfully(_ viewController: ASInterstitialViewController!) {
          asInterstitialVC?.show(from: self)
        }
        //MARK: AerServ Banner Callbacks
        func viewControllerForPresentingModalView() -> UIViewController! {
          return self  
        }
      }
      		

    Muting is turned off by default. If isMuted is set to NO, the control for mutability falls back to the setting on the AerServ + InMobi dashboard.

    Disabling Interstitial Animation

    To disable the animation for when the interstitial view controller is presented, use the hasAnimationflag within the ASInterstitialViewController object. This would be the animation of the interstitial ViewController scrolling up. When disabled, the ViewController will just appear. By default, this is disabled.

    • Objective-C
      #import <InMobiSDK/InMobiSDK.h>
      @interface ViewController() <ASInterstitialViewControllerDelegate>
      @property(nonatomic, strong) ASInterstitialViewController* asInterstitialVC;
      @end
      @implementation ViewController
      /**
       * Before loading a ad with ASInterstitialViewController, you'll need to set the flag to disable the animation.
       * Note: This will only affect AerMarket, S2S and tags. This function will not work with any SDK mediation.
       */
      - (void)loadAerServAd {
        self.asInterstitialVC = [ASInterstitialViewController viewControllerForPlacementID:@"1000741" withDelegate:self];
        self.asInterstitialVC.hasAnimation = NO; // The flag to toggle view controller's animation.
        [self.asInterstitialVC loadAd];
      }
      #pragma mark - Aerserv Interstitial Callbacks
      - (void)interstitialViewControllerAdLoadedSuccessfully:(ASInterstitialViewController*)viewController {
        [viewController showFromViewController:self];
      }
      @end
      		
    • Swift
      class ViewController: UIViewController, ASInterstitialViewControllerDelegate {
        var asInterstitialVC: ASInterstitialViewController?
        /**
         * Before loading a ad with ASInterstitialViewController, you'll need to set the flag to disable the animation. 
         * Note: This will only affect AerMarket, S2S and tags. This function will not work with any SDK mediation.
         */
        func loadAerServAd {
          asInterstitialVC? = ASInterstitialViewController(forPlacementID: "1000741", with: self)
          asInterstitialVC?.hasAnimation = false; // The flag to toggle the view controller's animation.
          asInterstitialVC?.loadAd()
        }
        //MARK: AerServ Interstitial Callbacks
        func interstitialViewControllerAdLoadedSuccessfully(_ viewController: ASInterstitialViewController!) {
          asInterstitialVC?.show(from: self)
        }
      }
      		

    Please Note: Disabling the animation won't affect any SDK mediation. You will only see the animation disabled for ads coming from AerMarket, S2S and tags.

    iOS 12 Wifi Settings

    Enable XCode WiFi Settings

    From iOS 12 onwards Apple has introduced privacy settings to access WiFi details. If the publisher decides to share wifi details, they can take advantage of targeted ads. Benefits of ad targeting are that, the ads are more useful and meaningful to users.

    How to enable Access Wifi Information?

    1. Enable access WiFi information feature to your App ID.


    2. Enable access WiFi information feature for your target app from XCode capabilities.


    3. WiFi Access should get added to your App.entitlements file. If not please add the following code to your App.entitlements file.
              <dict>
                  <key>com.apple.developer.networking.wifi-info</key>
                  <true/>
              </dict>
      		

    AVAudioSession event changes in WKWebView

    WKWebView ignores AVAudioSessionCategory, Publisher can handle audio interruptions by registering to observe AVAudioSessionInterruptionnotification posted by AVAudioSession. Publisher should ensure minimum possible disruption, and the most graceful possible recovery, from the perspective of the user.

    Observing Audio Interruptions

    To handle audio interruptions, begin by registering to observe notifications of type AVAudioSessionInterruptionNotification.

        - (void)registerForAudioInterruptionNotification {
        AVAudioSession *audioSession = [AVAudioSession sharedInstance];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleAudioSessionInterruption:) name:AVAudioSessionInterruptionNotification object:audioSession];
    }
    - (void)handleAudioSessionInterruption:(NSNotification *)notification {
        NSNumber *interruptionType = [[notification userInfo] objectForKey:AVAudioSessionInterruptionTypeKey];
        NSNumber *interruptionOption = [[notification userInfo] objectForKey:AVAudioSessionInterruptionOptionKey];
        switch (interruptionType.unsignedIntegerValue) {
            case AVAudioSessionInterruptionTypeBegan: {
                /* the system has interrupted your audio session */
                /* Pause, Save State, Update UI */
                break;
            }
            case AVAudioSessionInterruptionTypeEnded: {
                if (interruptionOption && interruptionOption.unsignedIntegerValue == AVAudioSessionInterruptionOptionShouldResume) {
                    /* the interruption has ended */
                    /* Resume, Update State, Update UI */
                }
                break;
            }
        }
    }
    	

    The posted NSNotification instance contains a userInfo dictionary providing the details of the interruption. You can determine the type of interruption by retrieving the AVAudioSessionInterruptionType value from the userInfo dictionary. The interruption type indicates whether the interruption has begun or has ended. If the interruption type is AVAudioSessionInterruptionTypeEnded, the userInfo dictionary might contain an AVAudioSessionInterruptionOptions value.

    An options value of AVAudioSessionInterruptionOptionShouldResume is a hint that indicates whether your app should automatically resume playback if it had been playing when it was interrupted. Media playback apps should always look for this flag before beginning playback after an interruption. If it’s not present, playback should not begin again until initiated by the user. Apps that don’t present a playback interface, such as a game, can ignore this flag and reactivate and resume playback when the interruption ends.

    Please Note: There is no guarantee that a begin interruption will have a corresponding end interruption. Your app needs to be aware of a switch to a foreground running state or the user pressing a Play button. In either case, determine whether your app should reactivate its audio session.

    For more details, please refer to the following:

    1. https://developer.apple.com/documentation/avfoundation/avaudiosession/1616596-interruptionnotification
    2. https://developer.apple.com/library/archive/documentation/Audio/Conceptual/AudioSessionProgrammingGuide/HandlingAudioInterruptions/HandlingAudioInterruptions.html
  • Version History

    SDK 9.0

    • 9.0.0: 9/20/19

      - Changes to support iOS 13

      - New and improved Modularised SDK design

      - Add InMobiMediationSDK.framework to your project for AerServ Mediation.

      - Addressing issue with layering of FAN banners upon refresh

      - SKStoreProductViewController crash fix.

      - Removed Support for iOS 8.

      - Removed Support for AerServ Native ad format.

      - Removed UIWebView from InMobi SDK. Viewability Partners might be using it.

      - Size reduction for both Framework and ipa inflation.

      - Various Bug Fixes and performance improvements

      - Adapter updates for the following mediation partners:

      • MoPub - v5.9.0
      • Google Mobile Ads - v7.50.0

      - APIs Added

      • IMBanner Class + -(void)cancel;
      • IMInterstitial Class + -(void)cancel;
      - APIs Added
      • ASAdView Class
        - @property (nonatomic, assign) ASEnvironmentType env;
        - @property (nonatomic, assign) ASPlatformType platform;
        - @property (nonatomic, assign) BOOL isMuted;
        - @property (nonatomic, assign) BOOL outlineAd;
        - @property (nonatomic, assign) BOOL sizeAdToFit;
        - @property (nonatomic, assign) BOOL useHeaderBidding;
        - @property (nonatomic, strong) NSArray* keyWords;
        - @property (nonatomic, assign) BOOL allowAdvertiserCloseButton;
        - -(void)forceRefreshAd;
        - -(CGSize)adContentSize;
        - -(void)rotateToOrientation:(UIInterfaceOrientation)newOrientation;
        - -(void)play;
        - -(void)pause;

      • ASAdViewDelegate Protocol
        - -(void)willLeaveApplicatonFromAd:(ASAdView*)adView;
        - -(void)adSizeChanged:(ASAdView*)adView;
        - -(void)adView:(ASAdView*)adView didFireAdvertiserEventWithMessage:(NSString*)msg;

      • ASInterstitialViewController Class
        - @property (nonatomic, assign) ASEnvironmentType env;
        - @property (nonatomic, assign) ASPlatformType platform;
        - @property (nonatomic, assign) BOOL isMuted;
        - @property (nonatomic, assign) BOOL showOutline;
        - @property (nonatomic, assign) BOOL useHeaderBidding;
        - -(void)play;
        - -(void)pause;
      • ASInterstitialViewControllerDelegate Protocol
        - -(void)interstitialViewControllerAdInteraction:(ASInterstitialViewController*)viewController;
        - -(void)interstitialViewController:(ASInterstitialViewController*)viewController didFireAdvertiserEventWithMessage:(NSString*)msg;
    • 8.2.0: 8/5/19
      • Chrome Custom tabs support
      • Thread Optimizations
      • Bug Fixes for SDK and AudienceBidder Plugin
    • 8.1.2: 7/18/19
      • Size reduction
      • Support for Audience Bidding for DFP
      • New api to set slot size for Banner in Audience Bidding
    • 8.1.1: 6/19/19
      • Updated AdColony SDK support to 3.3.10
      • Updated Audience Network (Facebook) support to 5.3.1
    • 8.1.0: 5/14/19
      • DFP Plugin Support
      • Mopub Audience Bidding Plugin Keyword Handling
      • Bug fixes
    • 8.0.8: 4/17/19
      • Bug Fixes
    • 8.0.7: 4/05/19
      • Additional support for higher granularity keywords
    • 8.0.5: 3/11/19
      • Audience Bidder for the Mopub Plugin
      • Telaria Adapter Deprecation
      • Flurry Banner Adapter Deprecation
      • Applovin 3rd Party API Reporting updates
      • Chartboost 3rd Party API Reporting updates
      • Mediated SDK updates
      • Bug Fixes
    • 8.0.2: 12/13/18
      • Mediation bug Fixes
    • 8.0.1: 11/28/18
      • Unified InMobi + AerServ SDK

    exchange | InMobi Mediation (Android)

    Prerequisites

    Make sure that your Android application meets the following requirements before proceeding.

    • Android 4.2.2 (Jelly Bean, API 17) and higher. MRAID ads require API 19 and higher.
      Older Android versions may work but are not officially supported.
    • Google Play Services will adhere to the user’s ad tracking preferences. For more information, please see Google's website regarding their Advertising ID.

    Note: If you are using Android Studio 3.0+, you'll need to disable AAPT 2.0. To do this, you'll need to add the following to your gradle.properties:

    android.enableAapt2=false
    	

    Step 1: Integrating the SDK

    • Step 1.1: Download the InMobi SDK

      Download the InMobi Android SDK here.

      The SDK bundle contains all media adapters that we support. Prune the downloaded folder to retain the media adapters you need.

      Warning: Please remove all older versions of the InMobi SDK (8.X.X and older) and all older versions of theAerServ SDK. Otherwise, your code will not compile! Please reach out to your account manager if you have any questions.

    • Step 1.2: Adding the Required Libraries

      Add the following files to the app/libfolder within your project:

      • lib/InMobiSDK.aar
      • network-support/Adcolony/adcolony-3.x.x.jar
      • network-support/AppLovin/applovin-sdk-8.x.x.jar
      • network-support/Chartboost/chartboost-7.x.x.jar
      • network-support/Facebook/AudienceNetwork.aar
      • network-support/Flurry/flurryAds_9.x.x.jar
      • network-support/Flurry/flurryAnalytics_9.x.x.jar
      • network-support/MillennialMedia/mm-ad-sdk-6.x.x.aar
      • network-support/MoPub/mopub-sdk-5.x.x.jar
      • network-support/MoPub/mopub-volley-2.x.x.jar
      • network-support/MyTarget/mytarget-sdk-4.x.x.aar
      • network-support/RhythmOne/rhythmone-ads.jar
      • network-support/Tremor/TremorVideo.aar
      • network-support/Unity/unity-ads.aar
      • network-support/Vungle/adapter-rxjava-2.x.x.jar
      • network-support/Vungle/converter-gson-2.2.0.jar
      • network-support/Vungle/dagger-2.7.jar
      • network-support/Vungle/eventbus-2.x.x.jar
      • network-support/Vungle/gson-2.x.jar
      • network-support/Vungle/javax.inject-1.jar
      • network-support/Vungle/okhttp-3.x.x.jar
      • network-support/Vungle/okio-1.x.x.jar
      • network-support/Vungle/retrofit-2.x.x.jar
      • network-support/Vungle/rxjava-1.2.0.jar
      • network-support/Vungle/vungle-sdk-android-5.x.x.jar

      You will also need to add the following folder into your app/lib:

      • network-support/Adcolony/arm64-v8a
      • network-support/Adcolony/armeabi
      • network-support/Adcolony/armeabi-v7a
      • network-support/Adcolony/x86
      • network-support/Adcolony/x86_64

      These resources can all be found in the download along with the InMobi SDK.
      Please note that using any other version of these SDKs may cause issues and unintended behavior.

    • Step 1.3:Gradle settings

      You'll need to add the following settings to your application's build.gradle:

      android {
        defaultConfig { 
        }
        buildTypes {
          ...
        }
        sourceSets {
          main {
            jniLibs.srcDirs = ['libs']
          }
        }
      }
      repositories {
        ...
      }
      dependencies {
        implementation 'com.android.support:appcompat-v7:25.3.1'
        implementation 'com.android.support:support-annotations:25.0.1'
        implementation 'com.android.support:support-compat:25.0.0'
        implementation 'com.google.android.gms:play-services-ads:10.2.1'
        implementation 'com.google.android.gms:play-services-ads-identifier:16.0.0'
        implementation 'com.google.android.gms:play-services-basement:16.1.0'
        implementation 'com.google.android.gms:play-services-location:10.2.1'
        implementation 'com.squareup.picasso:picasso:2.71828'
        implementation(name:'AudienceNetwork', ext:'aar')
        implementation(name:'mm-ad-sdk', ext:'aar')
        implementation(name:'mytarget-sdk', ext:'aar')
        implementation(name:'TremorVideo', ext:'ext')
        implementation(name:'unity-ads', ext'aar')
      }
      		

      Specifically note the dependencies that were added. These dependencies are an aggregation of the required settings from the mediation partner.

    • Step 1.4:Android Manifest

      • Add the following Android permission and activities into your Android Manifest:
        <?xml version='1.0' encoding='utf-8'?>
        <manifest xmlns:android='http://schemas.android.com/apk/res/android' package='com.sample.myapp' >
          <!-- Required Permissions -->
          <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
          <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
          <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
          <uses-permission android:name="android.permission.BLUETOOTH" />
          <uses-permission android:name="android.permission.INTERNET" />
          <uses-permission android:name="android.permission.NFC" />
          <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
          <uses-permission android:name="android.permission.RECORD_AUDIO" />
          <uses-permission android:name="android.permission.VIBRATE" />
          <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
        <!-- Optional Permissions -->
        <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
        <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
        <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
        <application
        android:allowBackup='true'
        android:label='@string/app_name'>
            <!-- ONE by AOL Provider -->
            <provider
              android:name="com.millennialmedia.internal.utils.MediaContentProvider"
              android:authorities="${applicationId}.MediaContentProvider"
              android:grantUriPermissions="true"
              android:exported="false" />
            <!-- AdColony Activities -->
            <activity
              android:name="com.adcolony.sdk.AdColonyInterstitialActivity"
              android:configChanges="keyboardHidden|orientation|screenSize"
              android:hardwareAccelerated="true" />
            <activity
              android:name="com.adcolony.sdk.AdColonyAdViewActivity"
              android:configChanges="keyboardHidden|orientation|screenSize"
              android:hardwareAccelerated="true" />
            <!-- AppLovin Activities -->
            <activity
              android:name="com.applovin.adview.AppLovinInterstitialActivity"
              android:configChanges="orientation|screenSize" />
            <activity
              android:name="com.applovin.adview.AppLovinConfirmationActivity"
              android:configChanges="orientation|screenSize" />
            <!-- Chartboost Activities -->
            <activity
              android:name="com.chartboost.sdk.CBImpressionActivity"
              android:excludeFromRecents="true"
              android:hardwareAccelerated="true"
              android:theme="@android:style/Theme.Translucent.NoTitleBar.Fullscreen"
              android:configChanges="keyboardHidden|orientation|screenSize" />
            <!-- Flurry Activities -->
            <activity
              android:name="com.flurry.android.FlurryFullscreenTakeoverActivity"
              android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize" />
            <!-- MoPub Activities -->
            <activity
              android:name="com.mopub.mobileads.MoPubActivity"
              android:configChanges="keyboardHidden|orientation|screenSize" />
            <activity
              android:name="com.mopub.mobileads.MraidActivity"
              android:configChanges="keyboardHidden|orientation|screenSize" />
            <activity
              android:name="com.mopub.common.MoPubBrowser"
              android:configChanges="keyboardHidden|orientation|screenSize" />
            <activity
              android:name="com.mopub.mobileads.MraidVideoPlayerActivity"
              android:configChanges="keyboardHidden|orientation|screenSize" />
            <activity
              android:name="com.mopub.mobileads.RewardedMraidActivity"
              android:configChanges="keyboardHidden|orientation|screenSize" />
            <!-- Rhythm One Activities -->
            <activity
              android:name="com.rhythmone.ad.sdk.RhythmOneAdActivity"
              android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
              android:label="RhythmOneAdActivity"
              android:theme="@android:style/Theme.Translucent.NoTitleBar" />
            <!-- Telaria Activities -->
            <activity
              android:name="com.tremorvideo.sdk.android.videoad.Playvideo"
              android:configChanges="keyboardHidden|orientation|screenSize|screenLayout|smallestScreenSize"
              android:hardwareAccelerated="false"
              android:exported="false">
              <intent-filter>
                <action android:name="com.tremorvideo.sdk.android.videoad.Playvideo" />
            <!-- Vungle Activities -->
            <activity
              android:name="com.vungle.publisher.VideoFullScreenAdActivity"
              android:configChanges="keyboardHidden|orientation|screenSize|screenLayout|smallestScreenSize"
              android:theme="@android:style/Theme.NoTitleBar.Fullscreen" />
            <activity
              android:name="com.vungle.publisher.MraidFullScreenAdActivity"
              android:configChanges="keyboardHidden|orientation|screenSize|screenLayout|smallestScreenSize"
              android:theme="@android:style/Theme.Translucent.NoTitleBar.Fullscreen" />
        </application>
        </manifest>
        			

        Rhythm One does require that hardware acceleration is enabled for the application.

        Note: Not including the optional permission MAY negatively impact fill for the respective networks that use these permissions.

      • Step 1.5:Preparing Your App for Android P

        InMobi SDK is compatible with Android P (API level 28), the latest version of the Android platform. Android P onwards apps make connections over HTTPS by default. Though InMobi supports the adoption of HTTPS, the current setup requires our demand partners to support HTTPS as well. The publisher can change their settings to HTTP if it has an impact on the revenue potential.

    Step 2:Initialize the SDK

    • Youmustinitialize our SDK before loading any ads. We recommend that you invoke this initialization routine at least 10 seconds before you intend to show your first ad. We suggest you initialize the SDK during the onCreate() state within your main activity.

      Failing to initialize the SDK in a timely manner may cause the first ad request to timeout.

    • To initialize the SDK, invoke AerServSdk.init(activity<Activity>, placement<String>) on the AerServSdk class.
    • To set or update the General Data Protection Regulation (GDPR) user consent flag, you can either call AerServSDK’s setGdprConsentFlag method or pass it through the initialization method. Pass true for user consent if GDPR user consent was granted and false if user consent was denied or if unknown.
    /**
     * Start "pre-init".
     * @param context Context
     * @param siteId AerServ's "siteID" or "appId"
     */
    public static void init(final Context context, final String siteId)
    /**
     * Start "pre-init"
     * @param context Context
     * @param siteId AerServ's "siteID" or "appId"
     * @param gdprConsentFlag User consent for GDPR
     */
    public static void init(final Context context, final String siteId, final Boolean gdprConsentFlag);
    /**
     * Set the flag for user consent.
     * @param context Context. This is left in for legacy reason. Pre-unification, the AS stored the
     *                consentFlag inside the SharedPreferences. This meant we needed the context. At
     *                the same time, we don't want to remove this parameter for publisher already
     *                integrated with the older API.
     * @param gdprConsentFlag Users consent for GDPR.
     */
    public static void setGdprConsentFlag(@NonNull Context context, Boolean gdprConsentFlag);
    /**
     * Returns the consent flag for GDPR
     * @param context Context. This is left in for legacy reason. Pre-unification, the AS stored the
     *                consentFlag inside the SharedPreferences. This meant we needed the context. At
     *                the same time, we don't want to remove this parameter for publisher already
     *                integrated with the older API.
     * @return Returns the flag for user consent in GDPR
     */
    @Nullable
    public static Boolean getGdprConsentFlag(@NonNull Context context);
    	

    How to obtain the app ID:

    • Log in to the AerServ + InMobi platform.
    • Go to the 'Inventory' tab in the top navigation bar.
    • Click the 'Edit' icon next to the app whose ID you wish to obtain.
    • You will find the app ID at the very top of the page.

    Mediation Disclaimer: Please be advised that although we are GDPR compliant, we currently have no way to send GDPR compliance as well as user consent to our mediated SDK partners. Compliance responsibility and request handling will solely depend on the SDK mediated partner. Please contact your mediated partners to avoid any issues and/or complications.

    Step 3: Displaying Banner Ads

    • Create an instance of the AerServBanner object. One way of doing this is to define it in your Activity's layout file, e.g. activity_main.xml. The following example will create a 320x50 banner within the MainActivity:
        <com.aerserv.sdk.AerServBanner
        android:id='@+id/banner'
        android:layout_width='320p'
        android:layout_height='50dp'
        android:layout_alignParentBottom='true'
        android:layout_centerHorizontal='true'
        android:gravity='center_horizontal' />
      		
    • In your code, obtain a reference to the AerServBanner instance and use it to call configure() and show().
      package com.sample.myapp;
      import android.app.Activity;
      import android.os.Bundle;
      import com.aerserv.sdk.AerServBanner;
      import com.aerserv.sdk.AerServConfig;
      import com.aerserv.sdk.AerServSdk;
      public class MainActivity extends Activity {
        private static final String APP_ID = "1000473";
        private static final String PLACEMENT_ID = "1024876";
        @Override
        public void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_main);
          AerServSdk.init(this, APP_ID);
        }
        /**
         * The banner doesn't need to be loaded in the main activity. However, the context that's passed 
         * in must also be a activity context. 
         */
        public void loadBannerAd() {
          AerServConfig config = new AerServConfig(this, PLACEMENT_ID);
          /**
           * After finding the view, you'll have to typecast the view into a AerServBanner object;
           */
          banner = (AerServBanner) findViewById(R.id.banner);
          /**
           * If you are not preloading, you MUST call show right after configure is called. Failing to do
           * so will result in unintended behavior.
           */
          banner.configure(config).show();
        }
      }
      		
    • Alternatively, you can also create the AerServ Banner instance programmatically.
      package com.sample.myapp;
      import android.app.Activity;
      import android.content.res.Resources;
      import android.os.Bundle;
      import android.util.TypedValue;
      import android.view.ViewGroup;
      import android.widget.RelativeLayout;
      import com.aerserv.sdk.AerServBanner;
      import com.aerserv.sdk.AerServConfig;
      public class MainActivity extends Acitvity {
        private static final String APP_ID = "1000473";
        private static final String PLACEMENT_ID = "1024876";
        private AerServBanner banner;
        @Override
        public void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_main);
          AerServSdk.init(this, APP_ID);
        }
        /**
        * AerServBanner is a subclass of the RelativeLayout class and can be modify as such. 
        * (e.g.RelativeLayout.setLayoutParam to change the width and height of the view)
        */
        public void loadBannerAd() {
          AerServConfig config = new AerServConfig(this, PLACEMENT_ID);
          banner = new AerServBanner(this);
          /**
           * Setting the height and width of the banner. This was previously done in the xml.
           */
          Resources r = getResources();
          float width = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 320, r.getDisplayMetrics());
          float height = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 50, r.getDisplayMetrics());
          banner.setLayoutParam(new RelativeLayout.LayoutParams(Math.round(width), Math.round(height)));
          /**
           * Add the banner as a child view. You MUST add the view into the UI before calling configure 
           * and show. In this example, we'll be adding it to the root view group.
           */
          ((ViewGroup) findViewById(android.R.id.content)).addView(banner);
          banner.configure(config).show();
        }
      }
      		

      If you’d like your app to listen to ad events and know when an ad has loaded or failed, implement an AerServEventListener and add it to your AerServConfig object:

      package com.sample.myapp;
      import android.app.Activity;
      import android.os.Bundle;
      import android.util.Log;
      import java.util.List;
      import com.aerserv.sdk.AerServBanner;
      import com.aerserv.sdk.AerServConfig;
      import com.aerserv.sdk.AerServEvent;
      import com.aerserv.sdk.AerServEventListener;
      import com.aerserv.sdk.AerServSdk;
      public class MainActivity extends Acitivity {
        private static final String APP_ID = "1000473";
        private static final String PLACEMENT_ID = "1024876";
        @Override
        public void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_main);
          AerServSdk.init(this, APP_ID);
        }
        public void loadBannerAd() {
          AerServEventListener listener = new AerServEventListener() {
            @Override
            public void onAerServEvent(AerServEvent event, List params) {
              switch (event) {
                case AD_LOADED:
                  // Execute some code when AD_LOADED event occurs.
                  break;
                case AD_DISMISSED:
                  // Execute some code when AD_DISMISSED event occurs.
                  break;
                case AD_FAILED:
                  // Execute some code when AD_FAILED event occurs.
                  break;
              }
            }
          };
          AerServConfig config = new AerServConfig(this, PLACEMENT_ID);
          /**
          * You'll have to pass the AerServEventListener through the the AerServConfig.
          */
          config.setEventListener(listener); 
          AerServbanner banner = (AerServBanner) findViewById(R.id.banner);
          banner.configure(config).show();
        }
      }
      		

    For additional events, please see Additional Settings section.

    • You should pause your banner when your app is backgrounded, and play it when the app resumes. You can also kill a banner.

      The methods are:

      package com.sample.myapp;
      import android.app.Activity;
      import android.os.Bundle;
      import com.aerserv.sdk.AerServBanner;
      import com.aerserv.sdk.AerServConfig;
      import com.aerserv.sdk.AerServSdk;
      public class MainActivity extends Activity {
        private static final String APP_ID = "1000473";
        private static final String PLACEMENT_ID = "1024876";
        private AerServBanner banner = null;
        @Override
        public void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_main);
          AerServSdk.init(this, APP_ID);
        }
        /**
         * You will want to call pause when the banner goes out of view. One example of this occuring is 
         * when the activity goes into the pause state, it prevents the banner from refresh in the 
         * background. This will occur when you switch the intent to another activity or when the
         * application goes into the background.
         */
        @Override
        public void onPause() {
          if(banner != null) {
            banner.pause();
          }
        }
        /**
         * Once the activity resumes and the banner is in view again, you can resume the banner refresh.
         */
        @Override
        public void onResume() {
          if(banner != null) {
            banner.play();
          }
        }
        /**
         * Once the activity is about to be destroyed, you'll want to call kill on the banner object to 
         * to ensure that all resources is cleaned.
         */
        @Override
        public void onDestroy() {
          if(banner != null) {
            banner.kill();
          }
        }
        public void loadBannerAd() {
          // The PLC 1024876 is for testing only and returns a 320x50 static HTML banner
          AerServConfig config = new AerServConfig(this, PLACEMENT_ID);
          AerServBanner banner = (AerServBanner) findViewById(R.id.banner);
          banner.configure(config).show();
        }
      }
      		
    • Pausinga banner will prevent it from refreshing, and killingit will remove it from the view.

    Step 4: Display Interstitial Ads

    You can configure and show a test interstitial ad in your Activity, as follows:

    package com.sample.myapp;
    import android.app.Activity;
    import android.os.Bundle;
    import com.aerserv.sdk.AerServSdk;
    import com.aerserv.sdk.AerServConfig;
    import com.aerserv.sdk.AerServInterstitial;
    public class MainActivity extends Activity {
      private static final String APP_ID = "1000473";
      private static final String PLACEMENT_ID = "1000741";
      @Override
      public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        AerServSdk.init(this, APP_ID);
      }
      public void loadInterstitialAd() {
          AerServConfig config = new AerServConfig(this, PLACEMENT_ID); 
          AerServInterstitial interstitial = new AerServInterstitial(config); 
          interstitial.show();
      }
    ]
    	

    If you’d like your app to listen to ad events and know when an ad has loaded or failed, implement an AerServEventListener and add it to your AerServConfig object:

    package com.sample.myapp;
    import android.app.Activity;
    import android.os.Bundle;
    import android.util.Log;
    import java.util.List;
    import com.aerserv.sdk.AerServConfig;
    import com.aerserv.sdk.AerServEvent;
    import com.aerserv.sdk.AerServEventListener;
    import com.aerserv.sdk.AerServInterstitial;
    import com.aerserv.sdk.AerServSdk;
    public class MainActivity extends Acitivity {
      private static final String APP_ID = "1000473";
      private static final String PLACEMENT_ID = "1000741";
      @Override
      public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        AerServSdk.init(this, APP_ID);
      }
      public void loadInterstitialAd() {
        AerServEventListener listener = new AerServEventListener() {
          @Override
          public void onAerServEvent(AerServEvent event, List params) {
            switch (event) {
              case AD_LOADED:
                // Execute some code when AD_LOADED event occurs.
                break;
              case AD_DISMISSED:
                // Execute some code when AD_DISMISSED event occurs.
                break;
              case AD_FAILED:
                // Execute some code when AD_FAILED event occurs.
                break;
            }
          }
        };
        AerServConfig config = new AerServConfig(this, PLACEMENT_ID);
        /**
         * You'll have to pass the AerServEventListener through the the AerServConfig.
         */
        config.setEventListener(listener); 
        AerServInterstitial interstitial = new AerServInterstitial(config); 
        interstitial.show();
      }
    }
    	
  • For additional events, please see Additional Settings section.
  • Preloading will start the process of fetching an ad and caching the video. It also informs the app earlier whether it will get an ad. We highly recommend that you use this feature whenever possible.

    To preload an interstitial ad, the steps are:

    • Create an AerServEventListener listener and listen to the PRELOAD_READY event. When the event is fired, the ad is successfully preloaded. Create an AerServConfig object, and set the above AerServEventListener as listener. Set preload flag to true in above AerServConfig object.
    • Instantiate an AerServInterstitial object, which will start the preload process. Do NOT call show() yet, as the ad is still being loaded. When you are ready to show the ad, call show(). You must only call show after you have received PRELOAD_READY event in step 1 above.

    Here is the code snippet for the above steps:

    package com.sample.myapp;
    import android.app.Activity;
    import android.os.Bundle;
    import android.util.Log;
    import java.util.List;
    import com.aerserv.sdk.AerServConfig;
    import com.aerserv.sdk.AerServEvent;
    import com.aerserv.sdk.AerServEventListener;
    import com.aerserv.sdk.AerServInterstitial;
    import com.aerserv.sdk.AerServSdk;
    public class MainActivity extends Activity {
      private static final String APP_ID = "1000473";
      private static final String PLACEMENT_ID = "1000741";
      private AerServInterstitial interstitial = null;
      private bool isAdLoaded = false; 
      @Override
      public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        AerServSdk.init(this, APP_ID);
      }
      /**
       * We check if the preload flag has been previously set. This is so that we don't waste a ad that 
       * has already been preloaded and calling another load won't necessary fill.
       */
      public void loadInterstitialAd() {
          if(isAdLoaded == false) {
            AerServEventListener listener = new AerServEventListener() {
              @Override
              public void onAerServEvent(AerServEvent event, List params) {
                switch (event) {
                  case PRELOAD_READY:
                    MainActivity.this.isAdLoaded = true;
                    // Anywhere after this point you can call showInterstitial();
                    break;
                  case AD_DISMISSED:
                    MainActivity.this.isAdLoaded = false;
                    Log.v(MainActivity.class.getSimpleName(), "Interstitial was shown.");
                    break;
                  case AD_FAILED:
                    MainActivity.this.isAdLoaded = false;
                    Log.v(MainActivity.class.getSimpleName(), "Interstitial failed to load.");
                    break;
                }
              }
            };
            AerServConfig config = new AerServConfig(this, PLACEMENT_ID)
              .setEventListener(listener)
              .setPreload(true); // This flag needs to be set for preload to work correctly.
            interstitial = new AerServInterstitial(config);
          } else {
            Log.v(MainActivity.class.getSimpleName(), "Interstitial has already been loaded");
          }
      }
      public void showInterstitial() {
        if(interstitial != null && isAdLoaded) {
          interstitial.show();
        } else {
          Log.v(MainActivity.class.getSimpleName(), "Interstitial has not been loaded");
        }
      }
    }
    	
  • Step 5: Additional Settings

    • Complete List of Events

      • Our SDK fires these additional AerServEvent events that can be caught by AerServEventListener:
      EVENT CALLBACK ENUM PURPOSE
      AD_CLICKED Ad was clicked or touched
      AD_COMPLETED Ad has completed
      AD_DISMISSED Ad has been closed
      AD_FAILED Ad failed to load
      AD_IMPRESSION Ad has shown
      LOAD_TRANSACTION This event will return a BuyerName as well as a BuyerPrice for the loaded ad.
      AD_LOADED Ad has been loaded
      PRELOAD_READY Ad has been preloaded
      VC_READY This event communicates the Virtual Currency (VC) name, amount, buyer name, and buyer price of the loaded ad. Please note that it does not imply the ad is preloaded nor does it imply that VC is rewarded. For those, you need to listen to PRELOAD_READY and VC_REWARDED events, respectively.
      VC_REWARDED Virtual Currency was rewarded
      VIDEO_COMPLETED Video has completed
      VIDEO_START Video ad has started
      SHOW_TRANSACTION This event communicates the Transaction Information of the loaded ad. This includes the buyer name and buyer price.
    • Virtual Currency

      • Virtual Currency (VC) allows you to reward users based on completed video views. You can configure the VC name and amount on SSUI, and the SDK will inform your app via events when the user has fully watched a video.
      • Here is the code example of how to listen to VC events:
        package com.sample.myapp;
        import android.app.Activity;
        import android.os.Bundle;
        import android.util.Log;
        import java.utils.List;
        import com.aerserv.sdk.AerServConfig;
        import com.aerserv.sdk.AerServEvents;
        import com.aerserv.sdk.AerServEventListener;
        import com.aerserv.sdk.AerServInterstitial;
        import com.aerserv.sdk.AerServVirtualCurrency;
        public class MainActivity extends Activity {
          private static final String APP_ID = "1000473";
          private static final String PLACEMENT_ID = "1000741";
          @Override
          public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            AerServSdk.init(this, APP_ID);
          }
          public loadInterstitialAd() {
            AerServEventListener listener = new AerServEventListener() {
              @Override
              public void onAerServEvent(AerServEvent event, List params) {
                switch (event) {
                  /**
                   * The VC_READY event will notify when we load the creative. Note that you can also get 
                   * the buyerName and buyer price throught the LOAD_TRANSACTION and SHOW_TRANSACTION event.
                   */
                  case VC_READY:
                    AerServVirtualCurrency vc = (AerServVirtualCurrency) params.get(0);
                    String name = vc.getName();
                    BigDecimal amount = vc.getAmount();
                    String buyerName = vc.getBuyerName();
                    BigDecimal buyerPrice = vc.getBuyerPrice();
                    // Add your logic here  
                    break;
                  /**
                   * The second callback will notify when the virtual currency has been rewarded. This will 
                   * only fire after the user has watch 100% of the video on a virtual currency enable 
                   * placement.
                   */
                  case VC_REWARDED:
                    AerServVirtualCurrency vc = (AerServVirtualCurrency) params.get(0);
                    String name = vc.getName();
                    BigDecimal amount = vc.getAmount();
                    String buyerName = vc.getBuyerName();
                    BigDecimal buyerPrice = vc.getBuyerPrice();
                    // Add your logic here  
                    break;
                }
              }
            };
            /**
             * Nothing change when using either of these AerServEvent. Both VC_READY and VC_REWARDED will 
             * work with banners and interstitial integration. 
             */
            AerServConfig config = new AerServConfig(this, PLACEMENT_ID)
              .setEventListener(listener)
            AerServInterstitial interstitial = new AerServInterstitial(config);
            interstitial.show();
          }
        }
        			

        Note: The buyer name and buyer price can be null, so if you intend to use those objects, make sure you check for a null value.

        • Use AerServConfig object to set user ID:
                        String USER_ID = "MyUserId"; 
                        String PLACEMENT_ID = "1000741"; 
                        AerServConfig config = new AerServConfig(MainActivity.this, PLACEMENT_ID).setUserId(USER_ID);
          				
        • We also support server VC callbacks. To use this feature please see the How to Set Up Rewarded Currency (Virtual Currency).The userId is required for VC enabled placements to be used on the server VC callback and for frequency capping.

          The userId is required for VC enabled placements to be used on the server VC callback and for frequency capping.

      • Ad Transaction Information

        During the process of showing an ad, the InMobi SDK will additionally return information pertaining to the buyer for your ad space and the price that the ad space was bought for.

        This detailed information can be found from these events:

        package com.sample.myapp;
        import android.app.Activity;
        import android.os.Bundle;
        import java.util.List;
        import com.aerserv.sdk.AerServConfig;
        import com.aerserv.sdk.AerServEvent;
        import com.aerserv.sdk.AerServEventListener;
        import com.aerserv.sdk.AerServInterstitial;
        import com.aerserv.sdk.AerServSdk;
        import com.aerserv.sdk.AerServTransactionInformation;
        public class MainActivity extend Activity {
          private static final String APP_ID = "1000473";
          private static final String PLACEMENT_ID = "1000741";
          @Override
          public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            AerServSdk.init(this, APP_ID);
          }
          public void loadInterstitialAd() {
            AerServEventListener listener = new AerServEventListener() {
              @Override
              public void onAerServEvent(AerServEvent event, List params) {
                switch (event) {
                  /**
                   * The LOAD_TRANSACTION event will contain the transaction information of the ad from the 
                   * first load attempt. The transaction information from this callback may be different 
                   * from the ad the produce the impression.
                   */
                  case LOAD_TRANSACTION:
                      AerServTransactionInformation vc = (AerServTransactionInformation) params.get(0);
                      String buyerName = vc.getBuyerName();
                      BigDecimal buyerPrice = vc.getBuyerPrice();
                      // Add your logic here  
                      break;
                  /**
                   * The didShowAdWithTransactionInfo callback will cotanin the transaction information of 
                   * the ad that produced a impression.  
                   */
                  case SHOW_TRANSACTION:
                      AerServTransactionInformation vc = (AerServTransactionInformation) params.get(0);
                      String buyerName = vc.getBuyerName();
                      BigDecimal buyerPrice = vc.getBuyerPrice();
                      // Add your logic here  
                      break;
                }
              }
            };
            /**
             * Nothing change with this implementation. Both LOAD_TRANSACTION and SHOW_TRANSACTION will work
             * with banners and interstitial integration. 
             */
            AerServConfig config = new AerServConfig(this, PLACEMENT_ID)
              .setEventListener(listener)
            AerServInterstitial interstitial = new AerServInterstitial(config);
            interstitial.show();
          }
        }
        			
      • Adding Publisher Keys

        Custom revenue reports can be generated via the SDK by assigning a dictionary object with publisher key value pairs to the pubKeys property. This is available for both interstitials and banners.

        package com.sample.myapp;
        import android.app.Activity;
        import android.os.Bundle;
        import java.util.HashMap;
        import java.util.Map;
        import com.aerserv.sdk.AerServConfig;
        import com.aerserv.sdk.AerServInterstitial;
        import com.aerserv.sdk.AerServSdk;
        public class MainActivity extends Activity {
          private static final String APP_ID = "1000473";
          private static final String PLACEMENT_ID = "1000741";
          @Override
          public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            AerServSdk.init(this, APP_ID);
          }
          public void loadInterstitialAd() {
            Map<String, String> pubkeys = new HashMap();
            pubkeys.put("key", "value");
            AerServConfig config = new AerServConfig(this, PLACEMENT_ID)
                    .setPubKeys(pubkeys); // Pass in the Map object.
            interstitial = new AerServInterstitial(config);
            interstitial.show();
          }
        }
        			

        For details about publisher keys, click here.

      • Enabling the Back Button(not supported in InMobi SDK 8.0.1)

        Enable the back button for interstitial. When the user clicks on the back button, the interstitial will exit. This is similar to when skip is enabled on the AerServ + InMobi dashboard. This will only work for ads coming from AerMarket, S2S or tags. By default, the backbutton is only enabled when the a becomes skippable.

        package com.sample.myapp;
        import android.app.Activity;
        import android.os.Bundle;
        import com.aerserv.sdk.AerServConfig;
        import com.aerserv.sdk.AerServInterstitial;
        import com.aerserv.sdk.AerServSdk;
        public class MainActivity extends Activity {
          private static final String APP_ID = "1000473";
          private static final String PLACEMENT_ID = "1000741";
          @Override
          public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            AerServSdk.init(this, APP_ID);
          }
          public void loadInterstitialAd() {
            AerServConfig config = new AerServConfig(this, PLACEMENT_ID)
            config
              /**
                * This will enable the back button when a interstitial is shown. This will do nothing 
                * when passed into a banner. This will also only work for ads coming form AerMarket, 
                * S2S and tags. By default, the back button is only enabled when skippability is
                * enabled.
                */
              .enableBackButton(true)
              /**
                * As previously stated, the back button is only enabled when skippability is enabled.
                * This is set through the AerServ + InMobi dashboard. You can also override the time for when
                * the back button is enabled.
                */
              .setBackButtonTimeout(5000);
            interstitial = new AerServInterstitial(config);
            interstitial.show();
          }
        }
        			
      • Header Bidding Requests

        The Header Bidding flag is now enabled by default, and "useHeaderBidding" has been deprecated and is no longer needed.

    Version History

    SDK 9.0

      9.0.0: 9/20/19
    • Modular SDK

      - Added an ability to integrate Mediation as a separate module.

    • Added support for Android 10
    • Support for Mopub 5.8
    • Interface Changes
      • - APIs added

        AerServTransactionInformation

        public String getCreativeID()

      • - APIs removed
        • InMobiNative

          public InMobiNative(Context context, long placementId, NativeAdListener listener)

          public void setNativeAdListener(NativeAdListener listener)

        • InMobiNative.NativeAdListener
        • InMobiBanner

          public void setListener(BannerAdListener listener)

        • InMobiBanner.BannerAdListener
        • InMobiInterstitial

          public InMobiInterstitial(Context context, long placementId, InterstitialAdListener2 listener)

          public void setInterstitialAdListener(InterstitialAdListener2 listener)

        • InMobiInterstitial.InterstitialAdListener2
    • Bug fixes and performance improvements
    • 8.2.1: 8/22/19
      • Bug Fixes for SDK and AudienceBidder Plugin
    • 8.2.0: 8/5/19
      • Chrome Custom tabs support
      • Thread Optimizations
      • Bug Fixes for SDK and AudienceBidder Plugin
    • 8.1.3: 7/18/19
      • Support for Audience Bidding for DFP
      • Bug Fixes
    • 8.1.2: 6/19/19
      • Updated AdColony SDK support to 3.3.10
      • Updated Audience Network (Facebook) support to 5.3.1
    • 8.1.1: 5/27/19
      • Support for new Picasso version 2.71828
      • Bug Fixes
    • 8.1.0: 5/14/19
      • DFP Plugin Support
      • Mopub Audience Bidding Plugin Keyword Handling
    • 8.0.9: 4/22/19
      • Bug Fixes
    • 8.0.8: 4/17/19
      • Bug Fixes
    • 8.0.7: 4/5/19
      • Bug Fixes
      • Updated AudienceBidder to v1.0.1
        • Support for granular keywords
        • Fixed issue with updateBid not working with MoPub's refresh
        • Replaced source file with a aar
        • Various API Changes (see documentation)
    • 8.0.5: 3/11/19
      • Audience Bidder for the Mopub Plugin
      • Telaria Adapter Deprecation
      • Flurry Banner Adapter Deprecation
      • Applovin 3rd Party API Reporting updates
      • Chartboost 3rd Party API Reporting updates
      • Mediated SDK updates
      • Bug Fixes
    • 8.0.1: 11/28/18
      • Unified InMobi + AerServ SDK

    exchange | Frequently Asked Questions

    Are you new to monetization ? To help you learn more about how InMobi works, we've put together these FAQs from publishers for your reference. If you do not find what you are looking for here or need further assistance, please contact your dedicated InMobi account manager or email us at sales@inmobi.com.

    But before we begin, let’s get a few things out of the way:

    • If you wish to download our latest SDK, please visit the Download SDK page.
    • If you have downloaded the SDK and wish to get started, then please visit the Getting Started page.

    Now that you know where to begin, let’s get to the questions.

    1. Integrating the SDK

    2. Creating Account

    3. Creating Placements

    4. Mediating InMobi

    5. Reporting

    6. Payment

    7. Compliance Guidelines

    exchange | Integrating InMobi with Mediation DRAFT

    Integrating InMobi with Mediation

    This guide is intended for publishers who want to integrate InMobi as a demand source on third party mediation platforms like Mopub, Google, Ironsource, Max, etc. You can integrate Banner, Interstitial, Native and Video ad formats (supported by InMobi) on the below mediation platforms.

    If you instead wish to use the InMobi mediation platform, then we would recommend getting started here.

    Prerequisites

    Download InMobi SDK here and get started with an InMobi account here.

    Mediation Platforms Supported

    Mediation Platform Mediation SDK Version Supported InMobi SDK & Adapters Integration Documentation
    MoPub
    • iOS 5.9.0
    • Android 5.8.0
    InMobi SDK 900

    InMobi SDK 900 Download Adapter: iOS | Android

    Visit
    Google AdMob
    • iOS 7.50.0
    • Android 18.2.0

    InMobi SDK 900 Download Adapter: iOS | Android

    Visit
    Google (Open Bidding)
    • iOS 7.50.0
    • Android 18.2.0

    InMobi SDK 7.3.0: Download Adapter

    Visit
    ironSource
    • iOS 6.8.5.0
    • Android 4.3.1

    InMobi SDK 7.2.1: Download Adapter

    Visit
    Applovin/Max Contact Applovin

    Contact Applovin

    Visit
    Appodeal
    • iOS 2.5.10
    • Android 2.5.8

    InMobi SDK 7.2.7: Download Adapter

    Visit
    Fyber
    • iOS 8.21.0
    • Android 9.56.0

    InMobi SDK 7.1.1: Download Adapter

    Visit

    We would highly recommend following the partner integration guidelines to know more about the specific mediation partner or adding InMobi as a demand source and setting up placements for mediation.

    exchange | Audience Bidding (Header Bidding)

    Audience Bidding is InMobi’s In-app Header Bidding solution. You can leverage unique audience intelligence to pre-fetch audience-driven bids from 70+ DSPs with a single call to our in-app header bidding SDK.

    Important:
    1. If you wish to get started with Audience Bidding, then begin by downloading our Mediation/Header Bidding SDK for iOS and Android.
    2. To create an account or set up placements, visit https://platform.aerserv.com/login

    Audience Bidding works hand-in-hand with your existing mediation platform. The following guides will help you get started with:

    • Audience Bidding for Mopub
    • Audience Bidding for Google DFP
      • iOS - Coming soon!
      • Android - Coming soon!

    Here's how Audience Bidding will help you:

    1. Revenue Optimization:

      Boost in-app revenue with dynamic bids optimized for each user.
      Maximize fills and revenue by increasing inventory exposure through simultaneous requests to 70+ DSPs that have global access to high intent advertisers.

    2. Enriched Supply:

      Secure your in-app revenue by differentiating your supply path.
      Stand out as enriched supply in a crowded marketplace by augmenting your inventory with high quality audience signals while working directly with the industry’s most preferred demand partners.

    3. Optimized Trafficking:

      Optimize your demand partnerships with smart bids across price points.
      Challenge your existing waterfall with pre-fetched bids across price points with a single SDK call. Get the most optimal bid through unified auctions.

    4. User Growth and Retention:

      Identify and grow your high-value users through actionable audience insights.
      Know your user worth in ARPU by overlapping impression data with high quality carrier-verified audiences. Get in-depth visibility into user intent as well as advertiser interest for users at a device/segment level.

    exchange | test for ios dfp

    Prerequisites

    Step 1: Integrating the SDK

    • Step 1.1: Download the InMobi SDK

      • Warning: Please remove all older versions of the InMobi SDK (7.X.X and older) and all older versions of the AerServ SDK. Otherwise, your code will not compile! Please reach out to your account manager if you have any questions. If you are using CocoaPods, be sure to remove the 'aerserv-ios-sdk' pod from your podfile and only use the 'inmobi-ios-sdk' pod.
    • Step 1.2: Add the Required Libraries

      • Add the following frameworks into your project from the InMobi SDK download:
      • Add the following folders into your project from the InMobi SDK download:
      • Note: When using any mediation through the InMobi SDK, it is highly recommended that you use the framework that is provided along with the InMobi SDK download. These versions have been tested by our team and using any other version may not be officially supported.
    • Step 1.3: General Settings

      • Under the General tab within your project's target, you'll need to add the follow settings:
        • Select all Device Orientation inside 'Deployment Info'.
        • Add the following dependencies to Linked Frameworks and Libraries:
        One or more of the mediation adapters that you selected requires these frameworks. For the SDKs to work properly, you MUST includes these frameworks into your project.
    • Step 1.4: Create a bridging header (Swift Only)

      • You will need to create a bridging header if your application is built with Swift. The bridging header exposes the Objective-C implementation to Swift. To create the bridging header, you'll need to do the following:
        1. Create a new header file, InMobiSDK-Bridging-Header.h.
        2. Add the following entry to the Bridging Header:
          
          
          #import <InMobiSDK/InMobiSDK.h>
        3. Add the newly created header file's path to the target's Build Setting -> Linking -> Objective-C Bridging Header
    • Step 1.5: Build Settings

      • Add the following to the target's Build Setting -> Linking -> Other Flag:
    • Step 1.6: Info.plist

      • You will need to add the following entries into your info.plist:
        
        

        For iOS 9+, you will need to disable App Transport Security (ATS). Please refer here for more detail.
    • Step 1.7: Integrating DFP to InMobi Adapter

      Step 1.7.1 Non-Audience Bidding

      Perform the following steps to initiate non-Audience bidding:

      1.7.1.1 Add DFP to InMobi Adapter

      Add the following files from dist/network-support/Google/DFP-CustomEvents/ to your project.

      1.7.1.2 Configure Ad Setup on DFP Dashboard

      Enter the following information:

      • Class Name: Use one of the following class name.
        • For Banner: AerServDFPCustomEventBanner
        • For Interstitial: AerServDFPCustomEventInterstitial
      • Parameter: AerServ platform ad parameters, in JSON format.
      1.7.1.3 Map Plugin Events

      InMobi banner events are mapped to DFP's CustomEventBannerDelegate events, as follows:

      • -adViewDidLoadAd: → -customEventBanner:didReceiveAd:
      • -adViewDidFailToLoadAd:withError: → -customEventBanner:didFailAd:
      • -willPresentModalViewForAd: → -customEventBannerWillPresentModal:
      • -willLeaveApplicatonFromAd: → -customEventBannerWillLeaveApplication:
      • -adWasClicked: → -customEventBannerWasClicked: & -customEventBannerWillLeaveApplication:
      • -didDismissModalViewForAd: → -customEventBannerDidDismissModal:

      InMobi interstitial events are mapped to DFP's CustomEventInterstitialDelegate events, as follows:

      • -interstitialViewControllerDidPreloadAd: → -customEventInterstitialDidReceiveAd:
      • -interstitialViewControllerAdFailedToLoad:withError: → -customEventInterstitial:didFailAd:
      • -interstitialViewControllerWillDisappear: → -customEventInterstitialWillDismiss:
      • -interstitialViewControllerDidDisappear: → -customEventInterstitialDidDismiss:
      • -interstitialViewControllerWillAppear: → -customEventInterstitialWillPresent:
      • -interstitialViewControllerAdWasTouched: → -customEventInterstitialWasClicked: & -customEventInterstitialWillLeaveApplication:

      InMobi rewarded video events are mapped to DFP's GADRewardBasedVideoAdNetworkAdapterProtocol events, as follows:

      • -interstitialViewControllerDidPreloadAd: → -adapterDidRecieveRewardBasedVideoAd:
      • -interstitialViewControllerAdFailedToLoad:withError: → -adapter:didFailToLoadRewardBasedVideoAdwithError:
      • -interstitialViewControllerDidDisappear: → -adapterDidCloseRewardBasedVideoAd:
      • -interstitialViewControllerDidAppear: → -adapterDidOpenRewardBasedVideoAd:
      • -interstitialViewControllerAdWasTouched: → -adapterDidGetAdClick: & adapterWillLeaveApplication:
      • -interstitialViewControllerDidVirtualCurrencyReward:vcData: → -adapter:didRewardUserWithReward:



      Step 1.7.2 Audience Bidding

      Note: Contact your account manager for Audience Bidding placement setup.
      • Add the additional following framework file:

        to support the IMAB Custom event classes, you'll need an additional framework. You can find this in the following directory of your SDK download: dist/network-support/Google/

        InMobiABAdMobDFPPlugin.framework

        If you are updating your iOS SDK version from a prior version, ensure that you've updated all of these files. Otherwise, if this is your first time integrating, just ensure that you link these files in your project.

      To use the InMobi Audience Bidding SDK, here is how you can expect the flow to go:

      1. The InMobi Audience Bidder SDK will make an ad request and return a bid object
      2. The bid object from InMobi Audience Bidder will have an updated DFPRequest Object and have pricing keywords attached
      3. You then call loadRequest() with the DFPRequest  object as before
      4. If InMobi is selected to fill, The InMobi Audience Bidder SDK will handle the rendering

      Optionally, if you would like to handle the keywords yourself, you may also observe the below flow:

      1. The InMobi Audience Bidder SDK will make an ad request.
      2. The response from InMobi Audience Bidder will have an IMABBidResponse object
      3. You may query the object for the bid keyword, price, granular keyword, InMobi placement, and buyer.
      4. You would then append the bid keyword in customTargeting and set placement id with GADCustomEventExtras using IMABCustomEvent key to DFPRequest object.
      5. You would then call loadRequest() with the DFPRequest  object as before
      6. If InMobi is selected to fill, The InMobi Audience Bidder SDK will handle the rendering
      1.7.2.1 Enabling Audience Bidding Setup on DFP

      To enable Audience Bidding, you will need to do 2 things:

      1. Set up the yield group to use the specific keywords with pricing used by the IMAudienceBidder class.
      2. Update your existing DFP integration details.
      1.7.2.1.1 Setting Up the DFP Yield Groups
      1. Sign in to Google Ad Manager.
      2. Click Delivery > Yield groups.
      3. Click New yield group. Enter a unique yield group Name that's descriptive for reporting.
      4. Select the Ad format and Inventory type you wish to target with this yield group.
      5. Define Key values using the keyword: “IMAB” for different price points. Enter the keyword in the following format IMAB:0.00 (eg. IMAB:0.50)
      6. Then add/map the ad units to these keywords under Custom Targeting.

        DFP_setup_step_6_iOS.png

      7. Ad Exchange will be your default partner/demand source on the UI. Proceed to add additional third-party yield partner and select InMobi (as the ad network) to compete for the targeted inventory.

        DFP_setup_step_7_iOS.png

        Note: Please ensure that the CustomClass name is as follows for Banner and Interstitial

        • Banner: IMABCustomEventBanner
        • Interstitial: IMABCustomEventInterstitial

        Note: Label should be mentioned as: IMABCustomEvent.

      8. Click Save to confirm your changes without activating this yield group for delivery, or click Save and activate to confirm your changes and immediately approve this yield group for delivery.
      9. Once a yield group has been created and activated, Ad Manager is ready to begin using the yield group to fill requests.
      10. Banner Price Points

        Enter the keyword in the "Keyword targeting" in the following format IMAB:0.00 (ex. IMAB:0.50)

        eCPM

        Keyword

        eCPM

        Keyword

        <0.05

        IMAB:0.05

        1

        IMAB:1.00

        0.1

        IMAB:0.10

        1.2

        IMAB:1.20

        0.2

        IMAB:0.20

        1.4

        IMAB:1.40

        0.3

        IMAB:0.30

        1.6

        IMAB:1.60

        0.4

        IMAB:0.40

        1.8

        IMAB:1.80

        0.5

        IMAB:0.50

        2

        IMAB:2.00

        0.6

        IMAB:0.60

        2.5

        IMAB:2.50

        0.7

        IMAB:0.70

        3

        IMAB:3.00

        0.8

        IMAB:0.80

        3.5

        IMAB:3.50

        0.9

        IMAB:0.90

        >4.00

        IMAB:4.00

        Interstitial Price Points

        Enter the keyword in the "Keyword targeting" in this format IMAB:0.00 (ex. IMAB:0.50)

        eCPM

        Keyword

        eCPM

        Keyword

        <0.50

        IMAB:0.50

        7

        IMAB:7.00

        1

        IMAB:1.00

        8

        IMAB:8.00

        1.5

        IMAB:1.50

        9

        IMAB:9.00

        2

        IMAB:2.00

        10

        IMAB:10.00

        2.5

        IMAB:2.50

        12

        IMAB:12.00

        3

        IMAB:3.00

        14

        IMAB:14.00

        3.5

        IMAB:3.50

        16

        IMAB:16.00

        4

        IMAB:4.00

        18

        IMAB:18.00

        4.5

        IMAB:4.50

        20

        IMAB:20.00

        5

        IMAB:5.00

        22

        IMAB:22.00

        6

        IMAB:6.00

        >24.00

        IMAB:24.00

      1.7.2.1.2 Updating Integration Details for Audience Bidding

      For Audience Bidding, here are the required changes that you'll need to do in our code:

      1. Import the InMobi SDK
      2. The IMAudienceBidder is a part of the SDK and will be able to handle most of the functionality required for audience bidding.

        #import <InMobiSDK/InMobiSDK.h>
      3. Initialize InMobi Audience Bidder
      4. You MUST initialize the InMobi Audience Bidder before you make an ad request. Typically, the initialization step may take up to 10 seconds. The initialize method will take in your application site ID (from the InMobi platform). If you have problems finding this information, reach out to your account manager.

        Note: To set the General Data Protection Regulation (GDPR) user consent flag. Pass YES/true for user consent if GDPR user consent was granted and NO/false if user consent was denied or if unknown.

        [IMAudienceBidder initializeWithAppID:kASAppID andUserConsent:@{ IM_GDPR_CONSENT_AVAILABLE : YES }];

        Note:

        • If you would like for InMobi to handle keywords (thus simplifying your integration), follow the below steps for Option A.
        • If you would like to handle the keywords yourself instead, follow the steps for Option B. In addition, you will have to set in customTargeting and set placement id with GADCustomEventExtras using IMABCustomEvent key to DFPRequest object.
      5. Creating or Submitting a bid
        1. Option A: Make an ad request using the bid object

          For Option A, to easily support banner refresh and support subsequent ad requests to the InMobi Audience Bidder, we have a BidObject that you should use.The IMAudienceBidder methods will return a BidObject which you can then call our refreshBid on.

          • The +createBidForAdType: method will return a bidObject which you should retain a strong reference to:
            @property (strong, nonatomic) IMBidObject *bidObject;
          • Please ensure you maintain a strong reference to the DFPRequest:
            @property (strong, nonatomic) DFPRequest *bannerRequest;
          • The +createBidForAdType: method requires for you to pass in an adType, InMobi placement (PLC), DFPRequest, and delegate. Contact your InMobi account manager if you have any questions about this.
          • The adType ENUM: kIMBiddingAdTypeBanner, kIMBiddingAdTypeInterstitial.
          • The setBannerSlotSize:adSize method will use to set the banner size. By default banner size will be 320*50.
          • The +submitBid method will kick off the bidding process with the created bid object. You may review IMAudienceBidder.h for more information.

          A full example snippet for banner and interstitial is available below. InMobi will handle the keywords for you in this option:

          Banner Code Examples
          CGSize bannerAdSize = CGSizeMake(320, 50); CGSize bannerAdSize = CGSizeMake(300, 250); GADAdSize customAdSize = GADAdSizeFromCGSize(bannerAdSize); self.dfpRequest = [DFPRequest request]; self.dfpBanner = [[DFPBannerView alloc] initWithAdSize:customAdSize]; self.dfpBanner.rootViewController = self; self.dfpBanner.adUnitID = DFP_BANNER_ADUNIT_ID; self.dfpBanner.delegate = self;
          // Call createBidForAdType and retain a reference to the bid object to be utilized later self.bannerBidObject = [IMAudienceBidder createBidForAdType:kIMBiddingAdTypeBanner withPlacement:AS_BannerID_AB adObj:self.dfpRequest andDelegate:self];
          // Set the banner ad size [self.bannerBidObject setBannerSlotSize:bannerAdSize]; // Submit the bid to kick off the bidding process [self.bannerBidObject submitBid];
          Interstitial Code Examples
          self.dfpRequest = [DFPRequest request]; self.dfpnterstitial = [[DFPInterstitial alloc] initWithAdUnitID:DFP_INT_ADUNIT_ID]; self.dfpInter.delegate = self;
          // Call createBidForAdType and retain a reference to the bid object to be utilized later self.interstitialBidOBject = [IMAudienceBiddercreateBidForAdType:kIMBiddingAdTypeInterstitial withPlacement:AS_InterstitialID_AB adObj:self.dfpRequest andDelegate:self];
          // Submit the bid to kick off the bidding process [self.interstitialBidOBject submitBid];
        2. Option B: Submit a bid request using submitBidForAdType

          You will not be able to use the BidObject, and you will have to repeatedly call the +submitBidForAdType: method.

          @property (strong, nonatomic) IMBidObject *bidObject;
          • Please ensure you maintain a strong reference to the DFPRequest:
            @property (strong, nonatomic) DFPRequest *bannerRequest;
          • >
          • The +submitBidForAdType: or +submitBidForAdType:adSize method requires for you to pass in an adType, InMobi placement (PLC), and delegate. Contact your InMobi account manager if you have any questions about this.
          • The adType ENUM: kIMBiddingAdTypeBanner, kIMBiddingAdTypeInterstitial
          • The +submitBidForAdType method also will kick off the bidding process (no need to call +submitBid seperately). You may review IMAudienceBidder.h for more information.
          • A full example snippet for banner and interstitial is available below. You will handle the keywords in this example. Call submitBidForAdType and do not use a bid object.

            Banner code examples

            GADAdSize customAdSize = GADAdSizeFromCGSize(CGSizeMake(320, 250)); self.dfpRequest = [DFPRequest request]; self.dfpBanner = [[DFPBannerView alloc] initWithAdSize:customAdSize]; self.dfpBanner.rootViewController = self; self.dfpBanner.adUnitID = DFP_BANNER_ADUNIT_ID; self.dfpBanner.delegate = self;
            // Call submitBidForAdType if you plan to add keywords to the object yourself [IMAudienceBidder submitBidForAdType:kIMBiddingAdTypeBanner withPlacement:AS_BannerID_AB adSize:customAdSize andDelegate:self];

            Remember to add the banner to the view and call show on it once you get the bidReceived delegate callback. For more information about DFP  banner implementation, you can consult the relevant DFP documentation here: https://developers.google.com/ad-manager/mobile-ads-sdk/ios/banner

            Interstitial Code Examples

            self.dfpRequest = [DFPRequest request]; self.dfpnterstitial = [[DFPInterstitial alloc] initWithAdUnitID:DFP_INT_ADUNIT_ID]; self.dfpInter.delegate = self;
            // Call submitBidForAdType if you plan to add keywords to the object yourself [IMAudienceBidder submitBidForAdType:kIMBiddingAdTypeInterstitial withPlacement:AS_InterstitialID_AB andDelegate:self];

            Remember to call load on the interstitial once you get the bidReceived delegate callback. You can reference the section below as well to see an example. For more information about DFP interstitial implementation, you can consult the relevant DFP documentation here: https://developers.google.com/ad-manager/mobile-ads-sdk/ios/interstitial.

            Also, do remember to call show when the interstitial has loaded! (when you get the interstitialDidReceiveAddelegate callback from DFP)

      6. Implement the IMAudienceBidderDelegate interface
        1. Option A: The IMAudienceBidderDelegate has 2 methods that need to be implemented:
          • -audienceBidderDidReceiveBidFor:
          • -audienceBidderDidFailBidFor:

          In either scenario (banner or interstitial), you will be returned a DFPRequest for banner and interstitial. If a bid was returned from createBidForAdType, you would then be given an updated DFPRequest  object. If a bid was not returned from createBidForAdType, you get returned a reference of the DFPRequest object with unmodified keywords. Below is an example delegate implementation covering both banner and interstitial:

          - (void)audienceBidderDidFailBidFor:(id)adObject withError:(NSError* ) error { // If the returned and updated adObject is a DFPRequest: if([adObject isKindOfClass:[DFPRequest class]]){ // Load the banner [self.dfpBannerloadRequest:self.dfpRequest]; // Or load the interstitial [self.dfpInterstitial loadRequest:self.dfpRequest]; } } - (void)audienceBidderDidReceiveBidFor:(id)adObject { // If the returned and updated adObject is a DFPRequest: if([adObject isKindOfClass:[DFPRequest class]]) { // Load the banner [self.dfpBanner loadRequest:self.dfpRequest]; // Or load the interstitial [self.dfpInterstitial loadRequest:self.dfpRequest]; } }
        2. Option B: If you prefer to handle keywords yourself, the IMAudienceBidderDelegate has 2 methods that need to be implemented:
          • -audienceBidderDidGenerateBidResponse:
          • -audienceBidderDidFailBidFor:

          For these methods,You would have to append the bid keyword in customTargeting and set placement id with GADCustomEventExtras using IMABCustomEvent key to DFPRequest object. In addition, you may be returned a IMBidResponse object.

          You may access the follow properties on the object:

          • NSString* placement - A NSString that describes the InMobi placement
          • NSString* buyer - A NSString that describes the buyer
          • NSNumber* price - A NSNumber that describes the price
          • NSString* keyword - A NSString that describes a keyword that should be provided to the DFPRequestad object
          • NSString* higherGranularityKeyword - A NSString that describes a granular keyword

          In either scenario (banner or interstitial), if a bid was returned from submitBidForAdType, you would then be given a IMBidResponse object. If a bid was not returned from submitBidForAdType, you do not get returned an IMBidResponse object and you can choose to add additional keywords at this step and/or call loadAd. Below is an example delegate implementation covering both banner and interstitial:

          // Use a Boolean to keep track so you don't call loadAd on the banner repeatedly. Boolean bannerLoaded = false; - (void)audienceBidderDidGenerateBidResponse:(IMBidResponse *)bidResponse {NSArray* bidResponseKey = [bidResponse.keyword componentsSeparatedByString:@":"]; NSDictionary *customTargetingDictionary; if (bidResponseKey.count == 2) {customTargetingDictionary = @{bidResponseKey.firstObject:bidResponseKey.lastObject}; } GADCustomEventExtras *extras = [[GADCustomEventExtras alloc] init]; [extras setExtras:@{kIMABLocalCacheKey : bidResponse.placement} forLabel:@"IMABCustomEvent"]; [self.dfpRequest registerAdNetworkExtras:extras]; // If the bid response placement is a banner if (bidResponse.placement == AS_BannerID_AB) { // Set or append the returned InMobi bidResponse keywords on the DFPRequest self.dfpRequest.customTargeting = customTargetingDictionary; // Set the local extras of the adview // If the banner has not yet been loaded, call loadAd on the updated DFPView      if (!bannerLoaded){ [self.dfpBanner loadRequest:self.dfpRequest]]; } } else if (bidResponse.placement == AS_InterstitialID_AB) {// Set or append the returned InMobi bidResponse keywords on the interstitial self.dfpRequest.customTargeting = customTargetingDictionary // Set the local extras of the interstitial [self.dfpBanner loadRequest:self.dfpRequest];
      7. Implement banner callbacks to support banner refresh with a new bid

        We support DFP automatic banner refresh in the InMobi Audience Bidder SDK for both implementation options, A and B.

        1. Option A: You'll need to include an +submitBid method call in the DFP adViewDidReceiveAd/ didFailToReceiveAdWithErrordelegate callbacks. This will allow us to provide a fresh bid each time the banner is refreshed.

          Note: The submitBid method should only be called after the banner bid object has been constructed to avoid unexpected behavior.

          - (void)adViewDidReceiveAd:(DFPBannerView *)adView { // Ensure that you do not call loadAd again on the DFP Ad View bannerLoaded = true; // On a successful load, call submitBid for the next refresh [self.bannerBidObject submitBid]; - (void)adView:(DFPBannerView *)adView didFailToReceiveAdWithError:(GADRequestError *)error // Ensure that you do not call loadAd again on the DFP Ad View bannerLoaded = true; // On a failed load, still call submitBid for the next banner refresh [self.bannerBidObject submitBid];
        2. Option B: You'll need to include a new +submitBidForAdType method call in the DFP adViewDidReceiveAd / didFailToReceiveAdWithErrordelegate callbacks. This will allow us to provide a fresh bid each time the banner is refreshed.
          - (void)adViewDidReceiveAd:(DFPBannerView *)adView { // Ensure that we do not call loadAd again on the DFPView bannerLoaded = true; // On a successful load, do a new submitBidForAdType for the next refresh [IMAudienceBidder submitBidForAdType:kIMBiddingAdTypeBanner withPlacement:AS_BannerID_AB andDelegate:self]; - (void)adView:(DFPBannerView *)adView didFailToReceiveAdWithError:(GADRequestError *)error { // Ensure that we do not call loadAd again on the DFPView bannerLoaded = true; // On a failed load, still call submitBidForAdType for the next banner refresh [IMAudienceBidder submitBidForAdType:kIMBiddingAdTypeBanner withPlacement:AS_BannerID_AB andDelegate:self];
      8. Get a new interstitial bid
        1. Option A: After an interstitial is shown, you can optionally call 'submitBid' on the interstitial bid object to get a new bid from the InMobi Audience Bidder.

          Note: The submitBid method should only be called after the interstitial bid object has been constructed to avoid unexpected behavior.

          [self.interstitialBidOBject submitBid];
        2. Option B: After an interstitial is shown, you can optionally call 'submitBidForAdType' on to get a new bid from the InMobi Audience Bidder.
          [IMAudienceBidder submitBidForAdType:kIMBiddingAdTypeInterstitial withPlacement:AS_InterstitialID_AB andDelegate:self];
      1.7.2.2 Testing your Audience Bidding Integration

      In order to test your Audience Bidding implementation, you will need to:

      • Make sure you enable test mode on your placement through the UI
      • Set up a line item with:
      1.  CPM 0.00
      2.  Keyword: IMAB:0.00

      Two ways to verify:

      1. Through Charles:
        1. In the ad request we send to DFP (https://pubads.g.doubleclick.net/gampad/ads), check under “Contents” & “JSON Text”, you should see a key value pair of: “cust_params: IMAB:0.00”
      2. Through DFP Reporting:
        1. Make sure the ad filled on testing.
        2. Make sure the numbers align for the newly generated line item at $0.00 (it might take a few minutes for DFP to report it).

    Step 3: Additional Settings (Optional)

    • Disabling App Transport Security for iOS 9+

      Select your application's Info.plist, right-click on it and open as source code. Copy the following code into your Info.plist's xml.
      
      
      <key>NSAppTransportSecurity</key> <dict> <key>NSAllowsArbitraryLoads</key><true/> </dict>
    • Muting Interstitial Ads (not supported in InMobi SDK 8.0.1 & 8.0.2)

      Video ads can be muted programmatically. This setting will not affect SDK mediation.
      
      
      #import <InMobiSDK/InMobiSDK.h> @interface ViewController() <ASInterstitialViewControllerDelegate, ASAdViewDelegate> @property(nonatomic, strong) ASInterstitialViewController* asInterstitialVC; @property(nonatomic, strong) ASAdView* asAdView; @end @implementation ViewController /** * Before loading a ad with ASInterstitialViewController, you'll need to set the mute flag. This function will * not work with any SDK mediation. */ - (void)loadInterstitialAd { self.asInterstitialVC = [ASInterstitialViewController viewControllerForPlacementID:@"1000741" withDelegate:self]; self.asInterstitialVC.isMuted = YES; // The flag to toggle mutability. [self.asInterstitialVC loadAd]; } /** * Before loading a ad with ASAdView, you'll need to set the mute flag. This function will not work with any SDK mediation. */ - (void)loadBannerAd { self.asAdView = [ASAdView viewWithPlacementID:@"1024876" andAdSize:ASBannerSize]; self.asAdView.delegate = self; self.asAdView.isMuted = YES; // The flag to toggle mutability. [self.view addSubview:self.asAdView]; [self.asAdView loadAd]; } #pragma mark - Aerserv Interstitial Callback - (void)interstitialViewControllerAdLoadedSuccessfully:(ASInterstitialViewController*)viewController { [viewController showFromViewController:self]; } #pragma mark - AerServ Banner Callback - (UIViewController*)viewControllerForPresentingModalView { return self; } @end
      
      
      class ViewController: UIViewController, ASInterstitialViewControllerDelegate, ASAdViewDelegate { var asInterstitialVC: ASInterstitialViewController? var asAdView: ASAdView? /** * Before loading a ad with ASInterstitialViewController, you'll need to set the mute flag. * This function will not work with any SDK mediation. */ func loadInterstitialAd() { asInterstitialVC? = ASInterstitialViewController(forPlacementID: "1000741", with: self) asInterstitialVC?.isMuted = true // The flag to toggle mutability. asInterstitialVC?.loadAd() } /** * Before loading a ad with ASAdView, you'll need to set the mute flag. This function will not work * with any SDK mediation. */ func loadBannerAd() { asAdView? = ASAdView(placementID: "1024876" andAdSize: ASBannerSize) asAdView?.delegate = self asAdView?.isMuted = true // The flag to toggle mutability. view.addSubview(banner!) asAdView?.loadAd() } //MARK: AerServ Interstitial Callbacks func interstitialViewControllerAdLoadedSuccessfully(_ viewController: ASInterstitialViewController!) { asInterstitialVC?.show(from: self) } //MARK: AerServ Banner Callbacks func viewControllerForPresentingModalView() -> UIViewController! { return self } }
      Muting is turned off by default. If isMuted is set to NO, the control for mutability falls back to the setting on the AerServ + InMobi dashboard.
    • Disabling Interstitial Animation

      To disable the animation for when the interstitial view controller is presented, use the hasAnimation flag within the ASInterstitialViewController object. This would be the animation of the interstitial ViewController scrolling up. When disabled, the ViewController will just appear. By default, this is disabled.
      
      
      #import <InMobiSDK/InMobiSDK.h> @interface ViewController() <ASInterstitialViewControllerDelegate> @property(nonatomic, strong) ASInterstitialViewController* asInterstitialVC; @end @implementation ViewController /** * Before loading a ad with ASInterstitialViewController, you'll need to set the flag to disable the animation. * Note: This will only affect AerMarket, S2S and tags. This function will not work with any SDK mediation. */ - (void)loadAerServAd { self.asInterstitialVC = [ASInterstitialViewController viewControllerForPlacementID:@"1000741" withDelegate:self]; self.asInterstitialVC.hasAnimation = NO; // The flag to toggle view controller's animation. [self.asInterstitialVC loadAd]; } #pragma mark - Aerserv Interstitial Callbacks - (void)interstitialViewControllerAdLoadedSuccessfully:(ASInterstitialViewController*)viewController { [viewController showFromViewController:self]; } @end
      
      
      class ViewController: UIViewController, ASInterstitialViewControllerDelegate { var asInterstitialVC: ASInterstitialViewController? /** * Before loading a ad with ASInterstitialViewController, you'll need to set the flag to disable the animation. * Note: This will only affect AerMarket, S2S and tags. This function will not work with any SDK mediation. */ func loadAerServAd { asInterstitialVC? = ASInterstitialViewController(forPlacementID: "1000741", with: self) asInterstitialVC?.hasAnimation = false; // The flag to toggle the view controller's animation. asInterstitialVC?.loadAd() } //MARK: AerServ Interstitial Callbacks func interstitialViewControllerAdLoadedSuccessfully(_ viewController: ASInterstitialViewController!) { asInterstitialVC?.show(from: self) } }
      Please Note: Disabling the animation won't affect any SDK mediation. You will only see the animation disabled for ads coming from AerMarket, S2S and tags.
    • iOS 12 Wifi Settings

      Enable XCode WiFi Settings From iOS 12 onwards Apple has introduced privacy settings to access WiFi details. If the publisher decides to share wifi details, they can take advantage of targeted ads. Benefits of ad targeting are that, the ads are more useful and meaningful to users.

      How to enable Access Wifi Information

      1. Enable access WiFi information feature to your App ID.



      2. Enable access WiFi information feature for your target app from XCode capabilities.



      3. WiFi Access should get added to your App.entitlements file. If not please add the following code to your App.entitlements file.
        
                      <dict>
                          <key>com.apple.developer.networking.wifi-info</key>
                          <true/>
                      </dict>
                    



      AVAudioSession event changes in WKWebView

      WKWebView ignores AVAudioSessionCategory, Publisher can handle audio interruptions by registering to observe AVAudioSessionInterruptionnotification posted by AVAudioSession. Publisher should ensure minimum possible disruption, and the most graceful possible recovery, from the perspective of the user.



      Observing Audio Interruptions

      To handle audio interruptions, begin by registering to observe notifications of type AVAudioSessionInterruptionNotification.

      
      - (void)registerForAudioInterruptionNotification {
          AVAudioSession *audioSession = [AVAudioSession sharedInstance];
          [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleAudioSessionInterruption:) name:AVAudioSessionInterruptionNotification object:audioSession];
      }
      
      - (void)handleAudioSessionInterruption:(NSNotification *)notification {
          
          NSNumber *interruptionType = [[notification userInfo] objectForKey:AVAudioSessionInterruptionTypeKey];
          NSNumber *interruptionOption = [[notification userInfo] objectForKey:AVAudioSessionInterruptionOptionKey];
          
          switch (interruptionType.unsignedIntegerValue) {
              case AVAudioSessionInterruptionTypeBegan: {
                  /* the system has interrupted your audio session */
                  /* Pause, Save State, Update UI */
                  break;
              }
              case AVAudioSessionInterruptionTypeEnded: {
                  if (interruptionOption && interruptionOption.unsignedIntegerValue == AVAudioSessionInterruptionOptionShouldResume) {
                      /* the interruption has ended */
                      /* Resume, Update State, Update UI */
                  }
                  break;
              }
          }
      }
      


      The posted NSNotification instance contains a userInfo dictionary providing the details of the interruption. You can determine the type of interruption by retrieving the AVAudioSessionInterruptionType value from the userInfo dictionary. The interruption type indicates whether the interruption has begun or has ended. If the interruption type is AVAudioSessionInterruptionTypeEnded, the userInfo dictionary might contain an AVAudioSessionInterruptionOptions value. An options value of AVAudioSessionInterruptionOptionShouldResume is a hint that indicates whether your app should automatically resume playback if it had been playing when it was interrupted. Media playback apps should always look for this flag before beginning playback after an interruption. If it’s not present, playback should not begin again until initiated by the user. Apps that don’t present a playback interface, such as a game, can ignore this flag and reactivate and resume playback when the interruption ends.

      Please Note: There is no guarantee that a begin interruption will have a corresponding end interruption. Your app needs to be aware of a switch to a foreground running state or the user pressing a Play button. In either case, determine whether your app should reactivate its audio session.

      For more details, please refer to the following:
      1. https://developer.apple.com/documentation/avfoundation/avaudiosession/1616596-interruptionnotification
      2. https://developer.apple.com/library/archive/documentation/Audio/Conceptual/AudioSessionProgrammingGuide/HandlingAudioInterruptions/HandlingAudioInterruptions.html

    Version History

      • 8.2.0: 8/5/19
        • Chrome Custom tabs support
        • Thread Optimizations
        • Bug Fixes for SDK and AudienceBidder Plugin
      • 8.1.2: 7/18/19
        • Size reduction
        • Support for Audience Bidding for DFP
        • New api to set slot size for Banner in Audience Bidding
      • 8.1.1: 6/19/19
        • Updated AdColony SDK support to 3.3.10
        • Updated Audience Network (Facebook) support to 5.3.1
      • 8.1.0: 5/14/19
        • DFP Plugin Support
        • Mopub Audience Bidding Plugin Keyword Handling
        • Bug fixes
      • 8.0.8: 4/17/19
        • Bug Fixes
      • 8.0.7: 4/05/19
        • Additional support for higher granularity keywords
      • 8.0.5: 3/11/19
        • Audience Bidder for the Mopub Plugin
        • Telaria Adapter Deprecation
        • Flurry Banner Adapter Deprecation
        • Applovin 3rd Party API Reporting updates
        • Chartboost 3rd Party API Reporting updates
        • Mediated SDK updates
        • Bug Fixes
      • 8.0.2: 12/13/18
        • Mediation bug Fixes
      • 8.0.1: 11/28/18
        • Unified InMobi + AerServ SDK
      • v3.1.6: 10/23/18
        • Bug Fixes
      • v3.1.5: 08/30/18
        • Dynamic Bidding through the MoPub Plugin
      • v3.1.3.2: 08/13/18
        • Bug Fixes
      • v3.1.3.1: 08/09/18
        • Bug Fixes
      • v3.1.3: 07/19/18
        • Bug Fixes
      • v3.1.2.2: 07/03/18
        • Bug Fixes
      • v3.1.2.1: 06/19/18
        • Moat SDK Updated to 3.5.0
        • Moat VPAID Support
        • Admob Mediation Rewarded Video Support
        • Admob Mediation Additional Banner Sizes Support
        • MyTarget iOS SDK Support
      • v3.1.1: 05/11/18
        • The ability to set and update GDPR user consent value on the SDK through the setGDPRWithUserConsent method
      • v3.1.0: 03/30/18
        • Open Auction Implementation
        • AdColony Dynamic Price Adapter Update
        • Vungle Dynamic Price Adapter Update
        • iPhone X Layout Support
        • AdColony SDK version update to 3.3.0
        • Admob/Google Mobile Ads SDK version update to 7.28.0
        • Applovin SDK version update to 4.8.3
        • Chartboost SDK version update to 7.1.0
        • Facebook SDK version update to 4.27.2
        • Flurry/Yahoo SDK version update to 8.4.0
        • Millennial Media (One by AOL) SDK version update to 6.7.0
        • Mopub SDK version update to 4.20.0
        • RhythmOne SDK version update to 6.41.2
        • Telaria/Tremor SDK version update to 3.15.0
        • Unity SDK version update to 2.1.2
      • v3.0.1: 03/08/18
        • Native support
        • InMobi SDK adapter support
        • Vungle adapter update to version 5.3.2
      • v2.42.2: 10/25/17
        • Addressed some minor bugs and included some optimizations.
      • v2.42.0: 10/11/17
        • Support for iOS 11
        • Removal of support for iOS 6.0
        • Updated Rhythm One Mediated SDK Adapter to version 6.4.2
        • Updated Yahoo/Flurry Mediated SDK Adapter to version 8.2.1
        • Updated MoPob Mediated SDK Adapter to version 4.16.0
        • Updated Facebook Mediated SDK Adapter to version 4.25.0
        • Updated AdColony Mediated SDK Adapter to version 3.2.1
        • Updated Chartboost Mediated SDK Adapter to version 7.0.1
      • v2.41.1: 08/22/17
        • Added logic to respect the end users device muting setting
        • Additional reporting optimization
        • Enabled bitcode to be configurable
      • v2.41.0: 08/08/17
        • Updated Mediation SDK Adapters
        • Tremor SDK update to 3.14.1.142
        • Millennial SDK update to 6.4.0
        • MoPub SDK update to 4.15.0
        • Flurry/Yahoo SDK update to 8.1.0
        • Facebook SDK update to 4.24.0
        • Enabled support for VAST 3.0
        • Resolved known issues with Admob and Appnexus mediated SDK
      • v2.40.1: 07/05/17
        • Header bidding support
        • Updated MoPubSDK to 4.13 in the Fabric Sample App
        • MoPub Sample App: The delegate is using the wrong parameter for MPAdView
        • Rewarded Video support through MoPub Plugin
        • Addressed some minor bugs and optimization
      • v2.39.5: 06/21/17
        • Enabled bitcode on the SDK
      • v2.39.4: 04/03/17
        • Updated AdMob SDK to 7.19.0
        • Updated MoPub SDK to 4.13.0
        • Updated AdColony SDK to 3.1.1
        • Removed camera and photo permission for MRAID
      • v2.39.3: 03/24/17
        • VPAID modification to prevent hanging on white screen after ad times out
        • VAST media files parsing modification for better media file selections
        • Added html decoder for encoded vast being passed in the ad parameters
        • Updated Vungle SDK to Version 4.0.9
        • Updated Facebook SDK to Version 4.20.2
      • v2.39.2: 03/13/17
        • Fixed issue with Banner Refresh
        • AdColony 3.1 Update
      • v2.39.1: 03/07/17
        • Update AppLovin to 3.5.2
        • Additional updates to the Ad Colony 3.0
        • Reallocation of ad serving logic onto the ad server
        • Adjustment to VAST/VPAID multiple media files
        • Refactored the wkwebview to prevent crashes
      • v2.38.2: 02/23/17
        • Updated AdColony SDK to 3.0
      • v2.38.1: 02/10/17
        • Updated AppNexus Plugin
      • v2.38.0: 02/07/17
        • Added support for ad pods
        • Minor bug fix to better handle the closing of end cards
      • v2.37.1: 01/12/17
        • Implemented Webkit support for iOS 10
        • Resolved Non-Public API issues with our mediated ad sources
        • Improved VPAID handling for iOS 9 and 10
        • Reporting and Event handling improvements
        • Adding API call to get SDK Version
      • v2.36.0: 11/30/16
        • Enabled the ability to support mute as a setting at the placement level
        • Added support for myTarget Mediation adapter
      • v2.35.1: 11/17/16
        • Improvements on handling 'init' calls
        • Improvements and fixes to Applovin, Adcolony and Rhythmn One mediation adapters
        • Fixed VAST errors
      • v2.35.0: 09/29/16
        • Updates to support iOS 10
        • Updated AdColony Privacy Config
        • Updated AdMob SDK to 7.11.0
        • Updated AppLovin SDK to 3.4.3
        • Updated Chartboost SDK to 6.5.1
        • Updated Facebook SDK to 4.15.1
        • Updated MillennialMedia SDK to 6.3.1
        • Updated Mopub SDK to 4.9.1
        • Updated Tremor SDK to 3.13.0.72
        • Updated Vungle SDK to 4.0.5
        • Minor Tracking improvements
      • v2.34.2: 09/22/16
        • Removed all non-public APIs that's preventing apps from getting approved from iTunes.
      • v2.34.0: 08/23/16
        • Updated Chartboost SDK to 6.4.7
        • Updated Applovin SDK to 3.4.0
        • Updated Adcolony SDK to 2.6.1.1
        • Changes to Rewarded Events
      • v2.33.0: 07/28/16
        • Added support for Rhythm One SDK Adapter
        • Updated events for reporting fixes
        • Improvement on handling VAST and VPAID creatives
      • v2.32.2: 07/07/16
        • Addressed minor rotation issues with VPAID ads
        • Fixed small memory leak issue
      • v2.32.1: 06/09/16
        • Updated events for reporting fixes.
      • v2.32.0: 06/06/16
        • Added support for Millennial Media SDK adapter
        • Enabled the capability to turn on MOAT for demand partners.
      • v2.31.0: 05/11/16
        • Supports ad campaigns that require end card
        • Fixes to Rewarded Video events with AdColony and Vungle
      • v2.30.0: 04/28/16
        • Added support for Tremor SDK adapter
        • Enabled publishers to view the mediated ad source name and price information, associated to the filled ad.
        • Support for VAST 3.0
        • Supports IAB MRAID Video Addendum
        • Minor fixes to the sample/test app
      • v2.29.6: 03/21/16
        • Add Serverside callback for Virtual Currency
        • Add an optional variable to associate ad requests with a user id.
      • v2.29.5: 02/16/16
        • Fix Banner Ad failed event on custom network adapter
      • v2.29.4: 02/01/16
        • Fix minor issue with MRAID
        • Enable Skip for Vast Banner
        • Improve Mediation Adapters
      • v2.29.3: 12/14/15
        • Add PreInit Method to Adcolony and AppLovin SDK mediation
      • v2.29.2: 12/07/15
        • Improve 3g connection buffering
        • Fix minor issue with DSYM
      • v2.29.0: 11/20/15
        • Centering MRAID Banners on Pre-iOS9 devices
        • Adding Parsing initial HTML to determine future orientation
        • Addressed the iOS 6 minor bug
      • v2.28.1: 11/02/15
        • Fix minor bug
      • v2.28.0: 09/22/15
        • Add method to pass in location for iOS8 in info.plist
        • Sample app change for iOS9 arbitrary (ATS) loads config update
        • Adding HTTPS SSL
        • Update and Improve client/server protocol
        • Add Publisher Key Values string method
        • Fix minor bugs
        • Post SDK binaries to Cocoapod
        • Improve vast on slower connection
        • Add New Network Support Adapters
          • Facebook Audience Network
          • Applovin
          • Chartboost
          • Unity Ads
          • Mopub SDK
      • v2.27.0.2: 08/17/15
        • Fixed minor bugs
        • Supports pre-cache Video
        • Implemented count down timer for Video Ads
        • Fixed quartile event bug
        • Updated AdMob SDK to 7.3.1.2
        • Resolved issue with keyword feature
      • v2.26.0: 07/8/15
        • Add VPAID for iOSsupport
        • Add Preload events in debugging log to sample app
        • Add Preload ready UI notification
        • Adjustment for logging to occur in sample app
        • Add VAST rigidity failover support
        • Fixed minor bugs
        • Fixed typo in event callbacks:
          • interstitialViewControllerAdFailedToLoad
          • interstitialViewControllerWillAppear
          • interstitialViewControllerDidAppear
        • Change preloadAd, virtualCurrencyLoad, virtualCurrencyReward — from adView to interstitial
      • v2.25.2: 06/08/15
        • Add Preloading Banner Video method
        • Add Video Completed event for banner
        • Separate Banner and interstitial Preload event
        • Add support for Full Screen video in Landscape mode
        • Update User agent parameter
      • v2.24.1: 06/02/15
        • Force full screen for video
        • Implemented Fabric/MoPub plugin
        • Fixed minor bug in iOS 6/7 crash
        • Enhance video ad completed dismiss animation
        • Improvesample app
        • Improve VAST parser
        • Add video size auto scaling support
      • v2.23.0: 05/01/15
        • Removed calls to clearCache
        • Add Preloading method with sdk & s2s mediation
        • Fixed minor bugs:
        • Added Show button to sample app
        • Removed alert dialogs in sample app
      • v2.22.0: 03/02/15
        • Update Vungle & AdColony Adapter
        • Minor bug fixes
      • v2.21.0: 02/19/15
        • Update AdMob adapter
        • Add Adcolony callback event
      • v2.20.0: 01/16/15
        • Fixed unregister throwing exception
        • Fixed null urls throwing exceptions
      • v2.19.0: 01/05/15
        • Changed interstitial delegate from assign to strong to prevent premature garbage collection
        • Added support for pub skip via vast wrappers
        • Sample apps now correctly min keyboard on loss of focus
      • v2.18.0: 12/05/14
        • Simple Integration API
        • Fixed user agent bug
        • Fixed vast wrapper bug
        • Play/pause banner
        • Play/pause interstitial
        • Fixed Keywords bug
      • v2.17.0: 11/04/14
        • Added vast 3.0 skip offset.  Including skip events as specified by vast 3.0 spec. Progress events will be in at a later time
        • Added the ability to add keywords to the call
        • Fixed bug where faulty unwrapped vasts were not failing over
        • Fixed user agent and removed system name which always returned iphone os
      • v2.16.0: 10/14/14
        • Timeout option on facades
        • Lat/Long now being sent on requests
        • adid and dnt being sent on requests
        • bunldeid being sent on request
        • Event is now firing correctly upon user close ad
        • Added YuMe adapter
        • Fixed lock screen on/off crash issue
        • Removed Adtech adapter
        • Fixed issue where Vungle/iAd/AdMob failover would fail due to newly added timeout feature
        • Updated AdMob SDKto 6.12.0
        • Removed ability to scroll banner ads
        • Added in bitmap check for failover
        • Fixed click through url encoding issue
        • Fixed AdColony upside down issue
      • v2.15.0: 10/02/2014
        • New adapters for the Yume and Adtech SDKs (Max version).
        • Fixed a crash when lock/unlock during ad playback.
        • Added a timeoutInterval property to ASAdView and ASInterstitialViewController.
        • Fixed a problem with lat/long not being passed correctly.
        • Tested for iOS 8 and iPhone 6
      • v2.14.0: 09/11/2014
        • Added SpecificMedia adapter.
      • v2.13.0: 08/08/2014
        • Updated the sample app menus.
      • v2.12.0: 08/07/2014
        • Added PhoneGap and Cocos2D adaptor and sample apps.
        • Updated the Unity adaptor.
      • v2.11.0: 08/04/2014
        • Video ads now resume when apps enter foreground.
        • Changed the user agent for ad related network calls.
        • Fixed certain missing video events.
      • v2.10.0: 06/20/14
        • Fixed random popup of 'Ad Failed to Load' alert after and ad rendered.
        • Added a Unity plug in and a sample Unity application.
        • Added AdColony, AdMob, iAds and Bungle SDK adapters.
      • v2.9.0: 06/10/14
        • Exposed clickthrough delegates.
        • Fixed a crash on malformed XML responses.
        • Forced landscape orientation on iPhone when playing videos.
        • Improved the sample app UI.
      • v2.8.0: 05/21/14
        • Fixed a crash when rendering certain video ads.
      • v2.7.0: 05/19/14
        • Added missing arm64 architecture to the SDK library.
      • v2.6.0: 05/16/14
        • Fixed sample project to run in simulator.
      • v2.3.0: 05/09/14
        • Initial release.
      The previous 1.x version are deprecated with the release of version 2.0. Version 2.0 provides support for new advanced features including client side failover and complex ad units.

    exchange | Getting Started new draft

    This guide is for all app developers and publishers who wish to monetize the ad inventory on their iOS or Android apps using the light weight InMobi SDK. Before you begin integrating the SDK into your app, please follow the steps below to set up an account with InMobi, register your app and create ad placements:

    Follow the simple steps and get started:

    Along the way, we have highlighted important guidelines and best practices to ensure you have everything in place to monetize your app quick and easy without our assistance. Ensure that you pause for a moment to read through these messages.

    Step 1: Signup with InMobi

    Now that you’re here and InMobi is the chosen one, what are you waiting for? Let’s get started with your account right away. To set up an InMobi account:

    1. Sign up as a publisher.
    2. A verification email with a link will be sent to your registered email address. Click on the link to complete the verification process. (This address will be used for any future communication about your account).
    3. On log in, choose the applicability pertaining to GDPR.

    Step 2: Register your App

    Once you have created an account, you can proceed to register your app with InMobi. The following steps are only meant for apps published in an app store. If you have an app that is yet to be published, visit Step 2A. Let's proceed.

    1. Click Add an app

    2. Select your relevant Operating System
    3. Enter a valid app store URL
    4. Click Add to list additional apps you wish to monetize.
    5. View your completed profile from the drop down next to your user name.

    Important: Please take a moment to read the compliance guidelines for properties directed to children below 13 years, and then select the check box if it applies to you.

    Step 2A: Register an Unpublished App

    If you have an unpublished app that is not live in the app store, just follow the simple steps below:

    1. Sign up as a Publisher.
    2. Complete the verification e-mail sent to the registered ID (The registered email ID here will receive all the communication).
    3. Choose the applicability pertaining to GDPR.
    4. Click Add app as shown in the dialog box.
    5. Choose operating system.
    6. When it's published, you can return to InMobi and link your app to its app store entry.

    Remember: For apps without a URL, the test mode is enabled by default. Once live, you can click the link to enter the URL on the dashboard as shown below.

    Step 3: Create Placements

    1. Select the relevant ad format to define the placement of your app.

    2. Scroll to your right/left to see more placements
    3. Enter details in Placement Name and click Create Placement
    4. Click Add Placement to create additional placements
    5. Once the setup is complete, you will get an overview of the placement details.

    Important:
    For Rewarded Video, please set the placement type to Interstitial.
    For Native ad units, please ensure the right format and aspect ratio is selected.

    Step 4: Update Payment Profile

    Create, verify and activate your payment profile to make your earnings tangible! InMobi follows a payout cycle of 60 days. This means that your earnings for a given month will be credited to you at the end of the 60-day payout cycle. You have the option of receiving your payouts via PayPal or wire transfer/RTGS.

    Note: This is a mandatory step and all publishers are requested to complete the details to monetize successfully.

    1. Select Earnings from the drop down next to your user name
    2. Select Add Account
    3. Add the following details:
      • Mode of Transfer
      • Bank Details
      • PAN Card Details
      • GST Details
    4. Once the setup is done, you will get an overview of your Payment Page.

    Note: Your Payment Id is available under your account summary as shown below. You will be able to view it, after the payment details you provided are verified and approved.

    Step 5: Control Ad Experience with Filters

    By using the blocking controls built into InMobi, you can curate the experience shown to the user by reviewing and controlling the ads that appear in your app. InMobi supports ad filters at three levels to control the ad experience:

    Level 1: Domain Filters

    You can block ads from specific URLs. For example, you might not want to show your competitors' ads on your apps.


    Level 2: URL or Keyword Filters

    You can block ads by filtering URLs /Keyword Filters based on their ad text or landing page URL. For example, you can prevent ads containing the text 'weapons' or 'virus' from serving on your site or app.


    Level 3: Category Filters

    You can block ads from specific categories which will not be served on your app. The categories range from Business, Art, Finance, Fashion etc. For example, an app meant for kids has the option to block ads from specific categories.

    Note: InMobi provides provision for blocking sensitive categories. You can block ads being served on content that includes topics such as politics, religion, mature content, gambling, etc.

    Note: Blocking any ad will lower your potential earnings as it reduces competition for your inventory by removing advertiser bids from the auction. We recommend blocking only those ads that you feel are absolutely irrelevant and inappropriate to your content or your users.

    exchange | Migrating to SDK 900

    InMobi’s iOS 12 and Android 10 compliant SDK 900 brings a superior monetization opportunity for your apps. The upgrade is super simple with just a drag-n-drop integration coupled with few compliance steps.


    The new integration guides are available here: iOS & Android.


    The latest version of InMobi SDK supports:

    • iOS - minimum iOS 9 and requires XCode 11 or later
    • Android - minimum Android 4.1 (API level 16) or later

    Migration prerequisites for iOS

    Wifi Settings

    Apple has introduced privacy settings to access WiFi details from iOS 12 onwards. To boost monetization and relevant user experience we encourage sharing WiFi details for targeted advertising. This can be done in three steps as shown below:

    Step 1: Enable ‘Access WiFi Information’ on your App ID.

    Step 2: Enable access ‘Access WiFi Information’ for your target app from XCode capabilities.

    Step 3: Ensure WiFi Access is added to your App.entitlements file.

    Migration prerequisites for Android

    1. Preparing For Android P

    InMobi SDK is compatible with Android P (API level 28), the latest version of the Android platform. In Android P and onwards, apps make connections over HTTPS by default. Though InMobi supports the adoption of HTTPS, the current setup requires our demand partners to support HTTPS as well. The publisher can change their settings to HTTP if it has an impact on the revenue potential.


    2. Preparing your app for AndroidX (JetPack)

    InMobi SDK is compatible with AndroidX (JetPack) library. In case your app uses the AndroidX library, then follow the standard guidelines by Google for migration by adding both the flags in build file.

    android.useAndroidX=true
    android.enableJetifier=true
    	

    It is highly recommended taht you upgrade Android Gradle plugin version to 4.1 or greater to avoid known issues in the jetifier which is fixed in the latest Gradle plugin version. To upgrade Android gradle plugin version, please refer to the Android developer documentation.

    3. New Bundle format - aar

    Android SDK has moved to a new format bundle, ‘aar’ for ease of integration. With InMobi SDK 800+, you do not need to add InMobiAdActivity into your application manifest.

    Note: InMobi SDK 900 and above will include the mandatory permissions automatically to the application manifest in order to proceed. Permissions added are as follows:

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    	

    It is highly recommended to include the library from jCenter by adding the following line in your app/build.gradle:

    implementation 'com.inmobi.monetization:inmobi-ads:9.0.0'
    	

    But in case you’re manually integrating the SDK, include the .aar file into the project using the following:

    implementation fileTree(dir: 'libs', include: ['*.aar'])
    	

    4. Changing the Manifest File (if migrating from SDK < 8XX)

    Please remove InMobiAdActivity element from your manifest as aar file will take care of that.

    5. Added API(s)

    The following API has been added:

    • InMobiBanner
      public void destroy()
    	

    6. Removed APIs

    The following legacy APIs have been removed :

    • InMobiNative
        public InMobiNative(Context context, long placementId, NativeAdListener listener)
        public void setNativeAdListener(NativeAdListener listener)
        public static void requestAd(.......)
      		
    • InMobiNative.NativeAdListener
    • InMobiBanner
      public void setListener(BannerAdListener listener)
      public static void requestAd(.......)
      		
    • InMobiBanner.BannerAdListener
    • InMobiInterstitial
      public InMobiInterstitial(Context context, long placementId, InterstitialAdListener2 listener)
      public void setInterstitialAdListener(InterstitialAdListener2 listener)
      public static void requestAd(.......)
      		
    • InMobiInterstitial.InterstitialAdListener2

    Note: For the project to compile, please remove any invocation of this API.

    exchange | Android Mopub new draft

    Integrating and monetizing InMobi SDK with Mopub is easy. Please refer this guide for integration instructions.

    You have access to the following ad types from InMobi via Mopub mediation.

    • Banner
    • Medium - Banner
    • Fullscreen (Interstitial, Full-screen Video Ads)
    • Rewarded Video
    • Native

    Before you begin setting up InMobi as an ad source on Mopub dashboard, it’s important that you create an InMobi account, register your app, configure placements and complete the payment information. You can learn more about it here.

    If you have completed the above steps, they you are all good to begin setting up InMobi as an adsource on Mopub. Let’s begin!

    Step 1: Configuring InMobi as an Ad Source on MoPub’s Dashboard

    Log on to your MoPub account and identify the ad units that you wish to monetize via InMobi. Then, navigate to the Networks tab.

    1. To monetize via InMobi, select Custom SDK Network. It allows you to integrate InMobi via MoPub with plug-n-play “Custom Events”.

      Note: You need both the InMobi SDK and the custom event for successful integration.

    2. Navigate to the specific ad unit that you want to monetize via InMobi.

    3. Enter the name of InMobi custom event class specific for that particular ad format as Custom Event Class value. For example, Interstitial Ad - the custom event is called: “com.inmobi.showcase.InMobiInterstitialCustomEvent”.

      Use fully qualified Custom Event class names. Here is the complete grid for custom events by ad unit type:

      Ad Unit

      Class Name

      Banner

      <your_package_name>.InMobiBannerCustomEvent

      Medium (300x250 banner)

      <your_package_name>.InMobiBannerCustomEvent

      Fullscreen

      <your_package_name>.InMobiInterstitialCustomEvent

      Rewarded Video

      <your_package_name>.InMobiRewardedCustomEvent

      Native

      <your_package_name>.InMobiNativeCustomEvent/

      <your_package_name>.InMobiNativeStrandCustomEvent

      Note: Please note that the package name <your_package_name> should be replaced with the actual package name in which the custom event classes are placed in the app.

    4. Your account ID is available in your InMobi account as illustrated in the screenshot below.

    5. Placement ID is present under the Placements section as illustrated in the screenshot below.

    6. Enter the Account ID and the Placement ID in the following format in the placeholder for Custom Event Class Data:
        {“placementid”: “<Enter your InMobi Placement ID here>”,”accountid”:”<Enter your InMobi Account ID here>”}
      		

      A sample input will look like this:

        {“placementid”:”1468850508657”,”accountid”:”2072131215e04a5ea20e25ffec1a7171”}
      		

    Step 2: Adding the SDK and Custom Event to your Project

    Option 1: Pulling the Latest SDK via JCenter

    If you are using Gradle to build your Android applications, you can pull the latest version of the SDK from JCenter as described below:

    1. Include JCenter in your top-level build.gradle file
      allprojects {
          repositories {
              jcenter()
          }
      }
      		
    2. Add the following line to the dependencies element in your application module’s build.gradle.
                  implementation 'com.inmobi.monetization:inmobi-ads:9.0.0'
      		
    3. Sync your Gradle project to ensure that the dependency is downloaded by the build system.

    Option 2: Adding the SDK Library to your Application Project

    Alternately, you can download the latest version of InMobi’s SDK here and copy the library to your application module’s libs/ directory.

    To add the library to your project’s dependencies, add this line to the dependencies element in your module’s build.gradle:

                implementation fileTree(dir: 'libs', include: ['*.aar])
    	
    Step 3: Adding and Verifying the Dependencies

    To monetize with the InMobi Ad SDK, you must add the following dependencies to your application module build.gradle:

    Google Play Services

    The InMobi SDK for Android needs the Google Play Services library to enable better ad targeting via the Google Play Advertising ID. Additionally, the SDK also uses the Google Play Services for getting a location fix, should the user consent to collecting their location.

    To add the Google Play Services client library to your application:

    1. Add the following lines to the application module’s dependency element:
                implementation 'com.google.android.gms:play-services-ads-identifier:17.0.0'
                implementation 'com.google.android.gms:play-services-location:17.0.0'
      		
    2. Sync your Gradle project to ensure that the dependencies are included.
    Chrome Custom Tab

    This is required to redirect the users to URLs outside InMobi WebView. To add the Chrome Custom library to your application:

    1. Add the following line to the application module's dependency element in the Gradle build script:
      implementation 'com.android.support:customtabs:28.0.0'
    2. Sync your Gradle project to ensure dependencies are included.

    Picasso Library

    The InMobi SDK for Android uses the popular Picasso library for loading the ad assets. To add the Picasso library to your application:

    1. Add the following line to the application module’s dependency element in the gradle build script.
                  implementation 'com.squareup.picasso:picasso:2.71828'
      		

    Note: Failure to include Picasso dependency in your application gradle scripts will cause interstitial ad requests to fail, thus affecting monetization of your app with the InMobi SDK.

    Support Library

    For supporting paged scroll of a deck of images or ads, you must use support-v4 library.

    To do so, add the following line to the application module’s dependency element in the Gradle build script.

                implementation '<strong>com.android.support:support-v4:28.0.0</strong>'
    	

    RecyclerView

    For supporting free scroll of a deck of images or ads, you must use RecyclerView.

    To do so, add the following line to the application module’s dependency element in the Gradle build script.

                implementation '<strong>com.android.support:recyclerview-v7:27.1.0</strong>'
    	

    Note: Failure to include RecyclerView dependency in your application gradle scripts will cause interstitial ad requests to fail, thus affecting monetization of your app with the InMobi SDK.

    Miscellaneous

    At times, including the InMobi SDK may cause the 64K limit on methods that can be packaged in an Android dex file to be breached. This can happen if, for example, your app packs a lot of features for your users and includes substantive code to realize this.

    If this happens, you can use the multidex support library to enable building your app correctly. To do this:

    1. Modify the defaultConfig mark your application as multidex enabled:
      defaultConfig {
                  applicationId "com.inmobi.samples"
                  minSdkVersion 15
                  targetSdkVersion 29 
                  versionCode 1
                  versionName "1.0.0"
                  multiDexEnabled true // add this to enable multi-dex
              }
      		
    2. Add the following line to the dependencies element in your application module’s build script.
                  compile 'com.android.support:multidex:1.0.3'
      		

    Step 3.1: Additional Configurations

    Granting Permissions

    It is highly recommended that you include ACCESS_FINE_LOCATION to enable better ad targeting. This is not a mandatory permission; however, including it will enable accurate ad targeting.

        <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    	

    For further improved targeting, you can add the ACCESS_WIFI_STATE and CHANGE_WIFI_STATE permissions to the manifest.

        <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
        <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
    	

    Hardware Acceleration

    Hardware acceleration allows you to display HTML5 video ads.

    To do this, add hardwareAccelerated:true element to the application tag.

    Proguard Configuration

    Proguarding helps to remove unused symbols and reduce the final application footprint. The following proguard directives should be added to your application’s proguard configuration file.

    -keepattributes SourceFile,LineNumberTable
    -keep class com.inmobi.** { *; }
    -keep public class com.google.android.gms.**
    -dontwarn com.google.android.gms.**
    -dontwarn com.squareup.picasso.**
    -keep class com.google.android.gms.ads.identifier.AdvertisingIdClient{
         public *;
    }
    -keep class com.google.android.gms.ads.identifier.AdvertisingIdClient$Info{
         public *;
    }
    # skip the Picasso library classes
    -keep class com.squareup.picasso.** {*;}
    -dontwarn com.squareup.okhttp.**
    # skip Moat classes
    -keep class com.moat.** {*;}
    -dontwarn com.moat.**
    # skip AVID classes
    -keep class com.integralads.avid.library.* {*;}
    	

    Important Prerequisites:

    Let’s pause for some checks before we begin initializing the SDK:

    Checkpoint 1: Preparing Your App for Android 10

    InMobi SDK is compatible with Android 10 (API level 29), the latest version of the Android platform.

    On Android P onwards, apps make connections over HTTPS by default. Though InMobi supports the adoption of HTTPS, the current setup requires our demand partners to support HTTPS as well. The publisher can change their settings to HTTP if it has an impact on the revenue potential.

    Checkpoint 2: Preparing Your App for AndroidX

    InMobi SDK is compatible with AndroidX (JetPack) library. In case your app uses the AndroidX library, then follow the standard guidelines by Google for migration by adding both the flags in build file.

              android.useAndroidX=true
              android.enableJetifier=true
    	

    It is highly recommended to upgrade Android Gradle plugin version to 4.1 or greater to avoid known issues in the jetifier which is fixed in the latest Gradle plugin version. To upgrade Android gradle plugin version please refer to Android developer documentation.

    Step 3.2: Add the Custom Event

    Add the custom events to your MoPub project. The custom events for different ad formats are also available as part of the sample code available here . The custom events are available under the relevant package structure. The code also has sample activities to illustrate how to mediate via MoPub SDK.

    Code Steps

    The code steps remain the same as they are for regular MoPub integration for fetching and loading an ad. Use the regular MoPub “ad unit id” to request and fetch an ad.

    Step 3.3: Passing user consent information to InMobi SDK

    The publishers monetizing in EEA region will have to pass user consent to InMobi SDK. The publishers can use consent gathering mechanism of their choice, and they will have to pass on this consent information to InMobi.

    • The publisher has to copy InMobiGDPR class into the project.
    • Use InmobiGDPR.grantConsent() or InmobiGDPR.revokeConsent() APIs to pass on user consent. Publisher will have to grant or revoke consent based on the consent provided by the user. It should be called once every session. In case grantConsent() is not called, we will presume that consent is not available for users belonging to EEA+UK+Switzerland region.
    • If the user consent is revoked at any point of time, the publisher has to call InmobiGDPR .revokeConsent() to notify InMobi about the same.
    • Use InMobiGDPR.isGDPRApplicable() to let InMobi know whether user belongs to GDPR compliant region.

    More Information

    You can see the complete sample code and example here

    The latest documentation and code samples for the MoPub SDK are available here.

    Step 5: Testing the Integration

    To ensure MoPub SDK relays the ad request to InMobi for testing:.

    1. Set manual Ad network optimization for every network including MoPub.
    2. Set manual eCPM floors for all networks keeping the eCPM floor for InMobi higher than other networks, this will ensure that the ad request gets relayed to InMobi for testing. For example for InMobi set the floor to $5 while MoPub marketplace is set to $0.05.


    Step 5.1 Enabling Key SDK Logs

    You can enable key SDK logs by adding the following line to your Activity while integrating the ad-units.

                InMobiSdk.setLogLevel(LogLevel.DEBUG);
    	

    You can also leverage feedback available on the diagnostics tab on the ad unit and ad request if you have enabled “Test Mode” on InMobi portal.

    Step 6: Advanced Configurations

    Pass the location information to allow better ad targeting.

    Recommended: If your app collects location from the user, we recommend passing it up, as impressions with location signal have higher revenue potential. InMobi SDK will automatically pass the location signals if available in the app. If you use location in your app, but would like to disable passing location signals to InMobi, then TURN OFF the “Location Automation” for your property on the InMobi dashboard.

    Otherwise, modify the Custom Event class for your ad-unit to pass on the data using the InMobi SDK API. Please see sample code for more details.

    InMobi supports the following parameters:

    Method Name

    Value

    Description

    setAgeGroup

    AgeGroup.BELOW_18

    AgeGroup.BETWEEN_18_AND_20

    AgeGroup.BETWEEN_21_AND_24

    AgeGroup.BETWEEN_25_AND_34

    AgeGroup.BETWEEN_35_AND_54

    AgeGroup.ABOVE_55





    The age group of the user

    setEducation

    Education.HIGH_SCHOOL_OR_LESS

    Education.COLLEGE_OR_GRADUATE

    Education.POST_GRADUATE_OR_ABOVE

    The education level

    • High school, or less
    • College, or graduate
    • Postgraduate, or above

    setAge

    Integer

    The age of the user

    setInterests

    Any String

    Any additional relevant description of the user, or their preferences, separated by commas. Valid acceptable values are mentioned below

    setPostalCode

    Any String

    The postal code (usually a 5 digit number)

    setAreaCode

    Any String

    The area code (part of the telephone number)

    setLanguage

    Any String

    The native language of the user (if known)

    setLocationWithCityStateCountry

    Any String

    Sets location with City, State, Country being passed

    setKeywords

    Any String

    Keywords to be passed in the ad request

    Here is a sample for setting up the InMobi SDK Demographic params. The publishers need to set the values of params as they want.

    InMobiSdk.setAreaCode("080");
    InMobiSdk.setEducation(Education.HIGH_SCHOOL_OR_LESS);
    InMobiSdk.setGender(Gender.MALE);
    InMobiSdk.setAge(23);
    InMobiSdk.setPostalCode("122009");
    InMobiSdk.setLogLevel(LogLevel.DEBUG);
    InMobiSdk.setLocationWithCityStateCountry("blore", "kar", "india");
    InMobiSdk.setLanguage("ENG");
    InMobiSdk.setInterests("dance");
    InMobiSdk.setYearOfBirth(1980);
    	

    exchange | Audience Bidding for MoPub (Android)

    Prerequisites

    Make sure that your Android application meets the following requirements before proceeding.

    • Android 4.2.2 (Jelly Bean, API 17) and higher. MRAID ads require API 19 and higher.
      Older Android versions may work, but are not officially supported.
    • Google Play Services will adhere to the user’s ad tracking preferences. For more information, please see Google's website regarding their Advertising ID.

    Note: If you are using Android Studio 3.0+, you'll need to disable AAPT 2.0. To do this, you'll need to add the following to your gradle.properties:
    android.enableAapt2=false

    Step 1: Integrating the SDK

    Step 1.1: Add the Required Libraries

    Option 1: Pulling the Latest SDK via JCenter

    If you are using Gradle to build your Android applications, you can pull the latest version of the SDK from JCenter as described below:

    1. Include JCenter in your top-level build.gradle file
      allprojects {
          repositories {
              jcenter()
          }
      }
      		
    2. Add the following line to the dependencies element in your application module’s build.gradle file.

      For Non-Audience Bidder:

      implementation 'com.inmobi.monetization:inmobi-mediation:9.0.0'
      		

      For Audience Bidder:

      implementation 'com.inmobi.monetization:inmobi-AB-plugin-mopub:1.0.5'
      		
    3. Sync your Gradle project to ensure that the dependency is downloaded by the build system.

    Option 2: Adding the SDK Library to your Application Project

    Alternately, you can download the latest version of InMobi’s SDK here and copy the library to your application module’s libs/ directory.

    Add the following files to the app/lib folder within your project.

    libs/InMobiSDK.aar
    libs/InMobiMediationSDK.aar
    	

    In case you’re integrating with InMobi Audience Bidding solution, you'll need an additional aar file (InMobiABMoPubPlugin-x.x.x.aar).

    These resources can all be found in the download along with the InMobi SDK.

    To add the library to your project’s dependencies, add this line to the dependencies element in your module’s build.gradle:

    implementation fileTree(dir: 'libs', include: ['*.aar])
    	

    The SDK bundle contains all media adapters that we support. Prune the downloaded folder to retain the media adapters you need.

    Warning: Please remove all older versions of the InMobi SDK (8.X.X and older) and all older versions of the AerServ SDK. Otherwise, your code will not compile! Please reach out to your account manager if you have any questions.

    Please note that using any other version of these SDKs may cause issues and unintended behavior.

    Step 1.2: Gradle settings

    You'll need to add the following settings to your application's build.gradle:

    android {
      defaultConfig { 
      }
      buildTypes {
        ...
      }
      sourceSets {
        main {
        }
      }
    }
    repositories {
      ...
    }
    dependencies {
    
      implementation 'com.google.android.gms:play-services-ads-identifier:16.0.0'
      implementation 'com.google.android.gms:play-services-basement:16.1.0'
      implementation 'com.google.android.gms:play-services-location:16.0.0'
      implementation 'com.squareup.picasso:picasso:2.71828'
    }
    	

    Step 1.3: Android Manifest

    Add the following Android permission into your Android Manifest:

    <?xml version='1.0' encoding='utf-8'?>
    <manifest xmlns:android='http://schemas.android.com/apk/res/android'  
      package='com.sample.myapp' >
    
      <!-- Required Permissions -->
      <uses-permission android:name="android.permission.INTERNET" />
    
      <!-- Optional Permissions -->
      <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
      <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
      <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
      <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
      
      <application
        android:allowBackup='true'
        android:label='@string/app_name'>
      </application>  
    </manifest>
    	

    Note: Not including the optional permission MAY negatively impact fill for the respective networks that use these permissions.

    Important Prerequisites

    • Checkpoint 1: Preparing Your App for Android 10

      InMobi SDK is compatible with Android 10 (API level 29), the latest version of the Android platform. On Android P onwards, apps make connections over HTTPS by default. Though InMobi supports the adoption of HTTPS, the current setup requires our demand partners to support HTTPS as well. The publisher can change their settings to HTTP if it has an impact on the revenue potential.

    • Checkpoint 2: Preparing Your App for AndroidX

      InMobi SDK is compatible with AndroidX (JetPack) library. In case your app uses the AndroidX library, then follow the standard guidelines by Google for migration by adding both the flags in build file.

      android.useAndroidX=true
      android.enableJetifier=true
      		

    Note: It is highly recommended to upgrade Android Gradle plugin version to 4.1 or greater to avoid known issues in the jetifier which is fixed in the latest Gradle plugin version. To upgrade Android gradle plugin version please refer to Android developer documentation.

    Step 1.4: Integrating MoPub Plugin

    Step 1.4.1: Audience Bidding

    Note: Contact your account manager for Audience Bidding placement setup.

    To use the InMobi Audience Bidding SDK, here is how you can expect the flow to go:

    • The InMobi Audience Bidder SDK will make an ad request and return a bid token
    • The bid token from the ad network will have an updated MoPub Ad Object and have pricing keywords attached
    • You then call loadAd() on the MoPub ad object as before
    • If InMobi is selected to fill, The InMobi Audience Bidder SDK will handle the rendering

    Optionally, if you would like to handle the keywords yourself, you may also observe the below flow:

    1. The InMobi Audience Bidder SDK will make an ad request and return a bid token
    2. The bid token from the ad network will have an IMABBidResponse object
    3. You may query the object for the bid keyword, price, granular keyword, InMobi placement, and buyer
    4. You would then append the bid keyword to MoPub's Adview
    5. You would then call loadAd() on the DFP ad object as before
    6. If InMobi is selected to fill, The InMobi Audience Bidder SDK will handle the rendering

    Step 1.4.1.1: Enabling Audience Bidding Setup on MoPub

    To enable Audience Bidding, you will need to do 2 things:

    1. Set up the line item to use the specific keywords with pricing used by the IMAudienceBidder class.
    2. Update your existing MoPub implementation.
    Step 1.4.1.1.1: Setting Up the MoPub Line Items

    Option 1 (Setting up Line Items Manually)
    1. Click on Orders -> Create Order
    2. Create a new order
      • Give your order a name (ex. Audience_Bidding_Test)
      • Enter in an advertiser name (ex. InMobi)
    3. Line item type
      • Give your line item a name (ex.IMAB_Banner_0.50)
      • Select type: Network Line Item
      • Select Network: Custom SDK network
      • Custom event class:
        • Banner: com.inmobi.plugin.mopub.IMABCustomEventBanner
        • Interstitial: com.inmobi.plugin.mopub.IMABCustomEventInterstitial
      • Custom event data: {}
      • Under "Budget & schedule", please enter the rate that matches what you have set up on your InMobi + AerServ dashboard for your eCPM (ex. 0.50)
    4. Ad unit targeting
      • Select the app and ad unit for your line item
    5. Audience Targeting
      • Enter the keyword in the "Keyword targeting" in this format IMAB:0.00 (ex. IMAB:0.50)
    eCPM Keyword eCPM Keyword
    0.01 IMAB:0.01 5.00 IMAB:5.00
    0.05 IMAB:0.05 6.00 IMAB:6.00
    0.10 IMAB:0.10 7.00 IMAB:7.00
    0.20 IMAB:0.20 8.00 IMAB:8.00
    0.30 IMAB:0.30 9.00 IMAB:9.00
    0.40 IMAB:0.40 10.00 IMAB:10.00
    0.50 IMAB:0.50 11.00 IMAB:11.00
    0.60 IMAB:0.60 12.00 IMAB:12.00
    0.70 IMAB:0.70 13.00 IMAB:13.00
    0.80 IMAB:0.80 14.00 IMAB:14.00
    0.90 IMAB:0.90 15.00 IMAB:15.00
    1.00 IMAB:1.00 16.00 IMAB:16.00
    1.10 IMAB:1.10 17.00 IMAB:17.00
    1.20 IMAB:1.20 18.00 IMAB:18.00
    1.30 IMAB:1.30 19.00 IMAB:19.00
    1.40 IMAB:1.40 20.00 IMAB:20.00
    1.50 IMAB:1.50 21.00 IMAB:21.00
    1.60 IMAB:1.60 22.00 IMAB:22.00
    1.70 IMAB:1.70 23.00 IMAB:23.00
    1.80 IMAB:1.80 24.00 IMAB:24.00
    1.90 IMAB:1.90 25.00 IMAB:25.00
    2.00 IMAB:2.00 26.00 IMAB:26.00
    2.50 IMAB:2.50 27.00 IMAB:27.00
    3.00 IMAB:3.00 28.00 IMAB:28.00
    3.50 IMAB:3.50 29.00 IMAB:29.00
    4.00 IMAB:4.00 30.00 IMAB:30.00
    Option 2 (Setting up Line Items with an Automated Script)

    Add a Chrome extension to your browser. Download extension here.

    1. Login to the MoPub Dashboard
    2. Create your order
    3. Create the first line item under the order
      • Line Item Setup:
        • Type & Priority: Network Line Item
        • Network: Custom SDK Network
        • Custom Event Class:
          • Banner: com.inmobi.plugin.mopub.IMABCustomEventBanner
          • Interstitial: com.inmobi.plugin.mopub.IMABCustomEventInterstitial
        • Example:

        • Under the "Audience Targeting" section:
          • Please enter a keyword in this format: IMAB:0.01
          • Example:

    4. Staying on the current tab, open the extension.
    5. Input the order name and the first line item name
    6. Click 'Run' to execute
    7. Wait for all the line items to be created
    Step 1.4.1.1.2: Technical Integration Details for Audience Bidding

    For the InMobi Audience Bidding solution, here are the required changes that we'll need to do in our code:

    • Integration Step 1: Add additional imports

    Our IMAudienceBidder will have most the necessary classes you'll need for working with our bidder.

    import com.inmobi.plugin.mopub.IMAudienceBidder;
    import com.inmobi.ads.InMobiAudienceBidder;
    	
    • Integration Step 2: Initialize MoPub SDK

    Remember to initialize the MoPub SDK. If you don't initialize, your application may not work as intended.

    MoPub.initializeSdk(this, sdkConfiguration, initSdkListener());
    	
    • Integration Step 3: Initialize the InMobi Audience Bidder

    You MUST initialize the InMobi Audience Bidder before you make an ad request. Typically, the initialization step may take up to 10 seconds. The initialize method will take in the current context and your application site ID (from the InMobi platform). If you have problems finding this information, reach out to your account manager.

    InMobiAudienceBidder.initialize(this, IMAB_SITE_ID);
    	

    You may also initialize the InMobi Audience Bidder SDK with a GDPR consent object.

    JSONObject consentObject = new JSONObject();
    
    try {
    consentObject.put("gdpr_consent_available", 1);
    
    } catch (JSONException e) {
    
    // Error handling here
    }
    
    InMobiAudienceBidder.initialize(this, IMAB_SITE_ID, consentObject);
    	
    • Integration Step 4: Get the singleton instance of the IMAudienceBidder

    Our IMAudienceBidder class will power the majority of the bidding functionality.

    IMAudienceBidder inMobiAudienceBidder = IMAudienceBidder.getInstance();
    	
    • Integration Step 5: Create a BidToken for later

    To easily support banner refresh and subsequent ad requests for the InMobi Audience Bidder, InMobi provides a BidToken that you may use. InMobi recommends retaining a reference to this. Our bid methods will return this BidToken which you can then call our refreshBid on. Our bid token constructor will require you to pass in an InMobi placement (PLC). Contact your InMobi account manager if you have any questions about this.

    private IMAudienceBidder.BidToken bidToken;
    	
    • Integration Step 6: Make an Ad request using the BidToken

    This step can be broken down into a couple smaller parts. Full example snippets for banner and interstitial is available below.

    • Ensure that your moPubView/MoPubInterstitial has already been constructed.
    • The banner bidder has a constructor method that will accept the current context, InMobi banner placement, MoPubView, and a listener (IMAudienceBidderBannerListener)
    • The interstitial bidder has a constructor method that will accept the current context, InMobi interstitial placement, MoPubInterstitial, and a listener(IMAudienceBidderInterstitialListener)
    • You may define multiple bidTokens.
    • Both banner and interstitial listeners will define a onBidReceived and onBidFailed callback method that must be implemented.

    Option A: If you would like for InMobi to handle the keywords (thus simplifying your integration), implement the IMAudienceBidderBannerListener or IMAudienceBidderInterstitialListener interface

    • For onBidReceived (meaning a bid was received from the InMobi Audience Bidder), you get returned an updated MoPub ad object. You then may call load()/loadAd() on this updated MoPub ad object.
    • For onBidFailed (meaning InMobi Audience Bidder failed to give a bid), you get returned a reference of the MoPub ad object with unmodified keywords. You then may call loadAd() on this MoPub ad object.

    Option B: If you would like to handle the keywords yourself instead, you may instead implement the IMAudienceBidderBannerKeywordListener / IMAudienceBidderInterstitialKeywordListener interface. In addition, you will have to call setLocalExtras on the MoPub ad view.

    • For onBidReceived (meaning a bid was received from the InMobi Audience Bidder), you get returned a IMABBidResponse. You can then retrieve the following pieces of information from the IMABBidResponse:
      1. getPlacement() - Returns a String that describes the InMobi placement
      2. getBuyer() - Returns a String that describes the buyer
      3. getPrice() - Returns a Double that describes the price
      4. getBidKeyword() - Returns a String that describes a keyword that should be provided to the MoPub ad object
      5. getGranularKeyword() - Returns a String that describes a granular keyword
    • For onBidFailed (meaning InMobi Audience Bidder failed to give a bid), you get returned an error. You then can call loadAd() on the original MoPub ad object.

    Banner Code Examples

    Option A: InMobi will handle the keywords for you in this snippet.

    // Use a Boolean to keep track so we don't call loadAd() on the banner repeatedly.
    public Boolean bannerLoaded = false;
    
    bannerBidToken = inMobiAudienceBidder.createBidToken(this, AB_BannerPLC, mopubViewWidth,
    mopubViewHeight, moPubView, new IMAudienceBidder.IMAudienceBidderBannerListener() {
    
    @Override
    public void onBidReceived(@NonNull final MoPubView m) {
    
        // Bid was received from InMobi Audience Bidder. Call loadAd() on the updated ad object.
    
        // If the banner has not yet been loaded, call loadAd() to load the ad into the view
        if (!bannerLoaded) {
            m.loadAd();
        }
    }
    @Override
    public void onBidFailed(@NonNull MoPubView m, @NonNull final Error error) {
    
        // No Bid received from InMobi Audience Bidder. Call loadAd() on the ad object.
    
        // If the banner has not yet been loaded, call loadAd() on the updated ad view
        if (!bannerLoaded) {
            m.loadAd();
        }
    }
    });
    
    // Call update bid to start this process
    bannerBidToken.updateBid();
    });
    	

    Option B: You will handle the keywords in this example. You will need to ensure mopub's adview localExtras is not null first. Below is an example of what you might do in your banner configuration code.

    Map localExtras = new HashMap();
    localExtras.put(IMAudienceBidder.AD_KEY, AB_BannerPLC);
    moPubView.setLocalExtras(localExtras);
    	

    The key difference with this integration path is that you'll need to call setKeywords() yourself by retrieving the value from the IMABBidResponse.

    // Use a Boolean to keep track so we don't call loadAd() on the banner repeatedly.
    public Boolean bannerLoaded = false;
    
    bannerBidToken = inMobiAudienceBidder.createBidToken(this, AB_BannerPLC, mopubViewWidth, mopubViewHeight, new IMAudienceBidder.IMAudienceBidderBannerKeywordListener() {
    
      @Override
      public void onBidReceived(IMAudienceBidder.IMABBidResponse imabBidResponse) {
    
          // Bid was received from InMobi Audience Bidder.
    
          // Parse the imaBidResponse for any additional information you need, and set them here as desired.
             moPubView.setKeywords(imabBidResponse.getBidKeyword());
    
          // If the banner has not yet been loaded, call loadAd to load the ad into the view
          if (!bannerLoaded) {
              moPubView.loadAd();
          }
      }
      @Override
      public void onBidFailed(Error error) {
    
          // No Bid received from InMobi Audience Bidder. Call loadAd on your MoPub view once you are ready.
    
          // Error handling here as desired
    
          // If the banner has not yet been loaded, call loadAd to load the ad into the view
          if (!bannerLoaded) {
              moPubView.loadAd();
          }
      }
    });
    
    // Call update bid to start this process
    bannerBidToken.updateBid();
    	

    For more information about MoPub banner implementation specifics, you can consult the relevant MoPub documentation here: https://developers.mopub.com/docs/android/banner/

    Interstitial Code Examples

    Option A: InMobi will handle the keywords for you in this snippet.

    interstitialBidToken = inMobiAudienceBidder.createBidToken(Activity.this,
    AB_InterstitialPLC, mInterstitial, new IMAudienceBidder.IMAudienceBidderInterstitialListener() {
    
        @Override
        public void onBidReceived(@NonNull final MoPubInterstitial m) {
    
            // Bid was received from InMobi Audience Bidder. You may call load() on the updated ad object.
            m.load();
        }
        @Override
        public void onBidFailed(@NonNull MoPubInterstitial m, @NonNull final Error error) {
    
            // No Bid received from InMobi Audience Bidder. You may call load() on the ad object.
            m.load();
        }
    
        // Then, call update bid to kick off the bidding process
        interstitialBidToken.updateBid();
    });
    	

    Option B: You will handle the keywords in this example. You will need to ensure mopub's adview localExtras is not null first. Below is an example of what you might do in your interstitial configuration code.

    Map localExtras = new HashMap();
    localExtras.put(IMAudienceBidder.AD_KEY, AB_InterstitialPLC);
    mInterstitial.setLocalExtras(localExtras);
    	

    The key difference with this integration path is that you'll need to call setKeywords() yourself by retrieving the value from the IMABBidResponse.

    interstitialBidToken = inMobiAudienceBidder.createBidToken(this, AB_InterstitialPLC, new IMAudienceBidder.IMAudienceBidderInterstitialKeywordListener() {
    
      @Override
      public void onBidReceived(IMAudienceBidder.IMABBidResponse imabBidResponse) {
    
          // Bid was received from InMobi Audience Bidder.
    
          // Parse the imaBidResponse for any additional information you need, and set them here as desired.
          mInterstitial.setKeywords(imabBidResponse.getBidKeyword());
    
          // Call load on the interstitial after all keywords have been set
          mInterstitial.load();
      }
      @Override
      public void onBidFailed(Error error) {
    
          // No bid received - you may call load on the interstitial after any additional keywords have been set
    
          // Error handling here as desired
          mInterstitial.load();
      }
    });
    
    // Then, call update bid to kick off the bidding process
    interstitialBidToken.updateBid();
    	

    Remember to then show the interstitial! Consult MoPub documentation here regarding interstitials: https://developers.mopub.com/docs/android/interstitial/

    public void onInterstitialLoaded(MoPubInterstitial interstitial) {
        if (interstitial.isReady()){  
           interstitial.show();  
        }
    }
    	
    • Integration Step 7: Implement Banner Callbacks to Support Banner Refresh

    InMobi supports MoPub's automatic banner refresh in the InMobi Audience Bidder SDK through MoPub Plugin SDK. You'll need to include an updateBid method call in the MoPub onBannerLoaded / onBannerFailed. This will allow us to provide a fresh bid each time the banner is refreshed.

    public void onBannerLoaded(MoPubView banner) {
    
        // Ensure that we do not call loadAd() again on the MoPubView
        bannerLoaded = true;
    
        // Update the bid for the next MoPub refresh ad call
        bannerBidToken.updateBid();
    }
    public void onBannerFailed(MoPubView banner, MoPubErrorCode errorCode) {
    
        // Ensure that we do not call loadAd() again on the MoPubView
        bannerLoaded = true;
    
        // Update the bid for the next MoPub refresh ad call
        bannerBidToken.updateBid();
    }
    	
    • Integration Step 8: Re-use the interstitial bid token

    You can also re-use the interstitial bid token. As an example, you might include this in the onInterstitialDismissed callback from MoPub.

    // Update bid for the next ad call
    interstitialBidToken.updateBid();
    	
    • Step 1.4.1.1.3: Testing your Audience Bidding Integration

    In order to test your Audience Bidding implementation, you will need to:

    • Make sure you enable test mode on your placement through the UI
    • Set up a line item with
      • CPM 0.00
      • Keyword: IMAB:0.00
    • Two ways to verify:
      • Through Charles:
        • In the ad request you send to Mopub (ads.mopub.com/m/ad), check:
        • Under "Contents" & "JSON Text", you should see a key value pair of: "q: keywords, testing, IMAB:0.00"
      • Through Mopub Reporting:
        • Make sure the ad filled on testing
        • Make sure the numbers align for the newly generated line item at $0.00 (it might take a few minutes for Mopub to report it).

    Step 1.4.2: Non-Audience Bidding

    • Step 1.4.2.1: Add the MoPub to AerServ Adapter

    Add the following files from dist/network-support/MoPub/AerServCustomEvents to your project:

    • network-support/MoPub/AerServBidder.java
    • network-support/MoPub/AerServBidListener.java
    • network-support/MoPub/AerServCustomEventBanner.java
    • network-support/MoPub/AerServCustomEventInterstitial.java
    • network-support/MoPub/AerServCustomEventRewardedInterstitial.java
    • network-support/MoPub/AerServPluginUtil.java
    • Step 1.4.2.2: Configure Ad Setting on MoPub Dashboard
    1. (Optional) Create a new AdUnit with the ad type you'd like to use AerServ with - you can use an existing AdUnit if one already exists.
    2. Now go to the 'Orders' tab and click on Create order. Creating a new 'Order' is optional. You can use an existing order if one already exists. If you decide to use an existing order, you will need to create a new Line Item instead.
    3. When creating a new Order/ Line Item, use the following parameters:
      • Advertiser: AerServ
      • Type & Priority: Network
      • Network: Custom Native Network
      • Class: Use one of the following class name. If you changed the package name, please change the classpath to correspond with the new package name.
        • For banner: com.mopub.mobileads.AerServCustomEventBanner
        • For interstitial: com.mopub.mobileads.AerServCustomEventInterstitial
        • For rewarded video: com.mopub.mobileads.AerServCustomEventRewardedInterstitial
      • eCPM: You will need to insert the eCPM from the AerServ dashboard. If you have any questions please contact our support.
      • Data: AerServ ad parameters, in JSON format. This field will take any additional parameter for the AerServ SDK. Refer to Advanced Topics - Server Parameters for more information.
      • Select the newly created AdUnit or use an existing AdUnit

    • Step 1.4.2.3: AerServ Ad Parameter

    AerServ server data that you entered on MoPub's web interface must be in JSON format. Currently we support these parameters:

    NAME TYPE REQUIRED DEFAULT DESCRIPTION
    placement String Yes N/A AerServ Placement
    Sample AerServ Ad Parameter
    {"placement": "1000741"}
    		
    • Step 1.4.2.4: Event Mapping

    AerServ banner events are mapped to MoPub's CustomEventBanner events, as follows:

    • AD_LOADEDonBannerLoaded()
    • AD_FAILEDonBannerLoaded()
    • AD_CLICKEDonBannerClicked()

    AerServ interstitial events are mapped to MoPub's CustomEventInterstitial events, as follows:

    • PRELOAD_READYonInterstitialLoaded()
    • AD_FAILEDonInterstitialFailed()
    • AD_IMPRESSIONonInterstitialShown()
    • AD_CLICKEDonInterstitialClicked()
    • AD_DISMISSEDonInterstitialDismissed()

    AerServ rewarded video events are mapped to MoPub's CustomEventRewardedVideo events, as follows:

    • PRELOAD_READYonRewardedVideoLoadSuccess()
    • AD_FAILEDonRewardedVideoLoadFailure()
    • VIDEO_STARTonRewardedVideoStarted()
    • AD_CLICKEDonRewardedVideoClicked()
    • AD_DISMISSEDonRewardedVideoClosed()
    • VC_REWARDEDonRewardedVideoCompleted()
    • Step 1.4.2.5: Error Codes

    AerServ adapter will fire the following MoPub errors using their AdRequest error enum:

    ADREQUEST ENUM CONDITION
    NETWORK_NO_FILL AerServ SDK fired AD_FAILED event. See AerServ SDK documentation for more details.

    Version History

    SDK 9.0

    • 9.0.0: 9/20/19
      • Modular SDK

        - Added an ability to integrate Mediation as a separate module.

      • Added support for Android 10
      • Support for Mopub 5.8
      • Interface Changes
        • - APIs added
          • AerServTransactionInformation

            public String getCreativeID()

          • InMobiBanner

            public void destroy()

        • - APIs removed
          • InMobiNative

            public InMobiNative(Context context, long placementId, NativeAdListener listener)

            public void setNativeAdListener(NativeAdListener listener)

          • InMobiNative.NativeAdListener
          • InMobiBanner

            public void setListener(BannerAdListener listener)

          • InMobiBanner.BannerAdListener
          • InMobiInterstitial

            public InMobiInterstitial(Context context, long placementId, InterstitialAdListener2 listener)

            public void setInterstitialAdListener(InterstitialAdListener2 listener)

          • InMobiInterstitial.InterstitialAdListener2
      • Bug fixes and performance improvements
    • 8.2.1: 8/22/19
      • Bug Fixes for SDK and AudienceBidder Plugin
    • 8.2.0: 8/5/19
      • Chrome Custom tabs support
      • Thread Optimizations
      • Bug Fixes for SDK and AudienceBidder Plugin
    • 8.1.3: 7/18/19
      • Support for Audience Bidding for DFP
      • Bug Fixes
    • 8.1.2: 6/19/19
      • Updated AdColony SDK support to 3.3.10
      • Updated Audience Network (Facebook) support to 5.3.1
    • 8.1.1: 5/27/19
      • Support for new Picasso version 2.71828
      • Bug Fixes
    • 8.1.0: 5/14/19
      • DFP Plugin Support
      • Mopub Audience Bidding Plugin Keyword Handling
    • 8.0.9: 4/22/19
      • Bug Fixes
    • 8.0.8: 4/17/19
      • Bug Fixes
    • 8.0.7: 4/5/19
      • Bug Fixes
      • Updated AudienceBidder to v1.0.1
        • Support for granular keywords
        • Fixed issue with updateBid not working with MoPub's refresh
        • Replaced source file with a aar
        • Various API Changes (see documentation)
    • 8.0.5: 3/11/19
      • Audience Bidder for the Mopub Plugin
      • Telaria Adapter Deprecation
      • Flurry Banner Adapter Deprecation
      • Applovin 3rd Party API Reporting updates
      • Chartboost 3rd Party API Reporting updates
      • Mediated SDK updates
      • Bug Fixes
    • 8.0.1: 11/28/18
      • Unified InMobi + AerServ SDK

    exchange | Audience Bidding for MoPub (iOS)

    Prerequisites

    • The following environments are required:
      • iOS 9+
      • XCode 11

    Step 1: Integrating the SDK


    • Step 1.1: Download the InMobi SDK

    Download the latest InMobi SDK below. We also provide the option to use CocoaPods!

    a. Direct SDK download here.

    The SDK bundle contains all media adapters that we support. Prune the downloaded folder to retain the media adapters you need.

    b. CocoaPods (Recommended)

    In the same directory as your YOUR_PROJECT.xcodeproj, create an empty file named Podfile and copy and paste the following:

    platform :ios, '9.0'
    target 'APP_NAME' do
          pod ‘InMobiABMoPubPlugin’
    end
    	

    Ensure your project has been closed. Using the terminal, navigate to the directory containing the Podfile and run the command: pod install. Once the installation finishes, use YOUR_PROJECT.xcworkspace to access your project moving forward.

    Inside the xcworkspace there should be a Pods directory included with a ios-sdk-pod sub-directory.

    Warning: Please remove all older versions of the InMobi SDK (8.X.X and older) and all older versions of the AerServ SDK. Otherwise, your code will not compile! Please reach out to your account manager if you have any questions. If you are using CocoaPods, be sure to remove the 'aerserv-ios-sdk' pod from your podfile and only use the 'InMobiMediationSDK' pod.

    • Step 1.2: Add the Required Libraries

    Add the following frameworks into your project from the InMobi SDK download:

    InMobiSDK.framework
    InMobiMediationSDK.framework
    	

    Note: When using any mediation through the InMobi SDK, it is highly recommended that you use the framework that is provided along with the InMobi SDK download. These versions have been tested by our team and using any other version may not be officially supported.

    • Step 1.3: General Settings

    • Under the General tab within your project's target, you'll need to add the following settings:
    • Select all Device Orientation inside 'Deployment Info'.
    • Add the following dependencies to Linked Frameworks and Libraries:
      • WebKit.framework
      • libxml2..tbd
      • libz.tbd
      • libsqlite.3.0.tbd

    One or more of the mediation adapters that you selected requires these frameworks. For the SDKs to work properly, you MUST include these frameworks into your project.

    • Step 1.4: Create a bridging header (Swift Only)

    You will need to create a bridging header if your application is built with Swift. The bridging header exposes the Objective-C implementation to Swift. To create the bridging header, you'll need to do the following:

    1. Create a new header file, InMobiSDK-Bridging-Header.h.
    2. Add the following entry to the Bridging Header:
      #import <InMobiSDK/InMobiSDK.h>
      		
    3. Add the newly created header file's path to the target's Build Setting -> Linking -> Objective-C Bridging Header
    • Step 1.5: Build Settings

    Add the following flags to the target's Build Setting -> Linking -> Other Linker Flag:

    -ObjC

    • Step 1.6: Info.plist

    You will need to add the following entries into your info.plist:

    <key>NSLocationWhenInUseUsageDescription</key>
    <string>Location is used to help target content to your general area</string>
    <key>NSPhotoLibraryUsageDescription</key>
    <string>Some ad content may require access to the photo library.</string>
    <key>NSCameraUsageDescription</key>
    <string>Some ad content may access camera to take picture.</string>
    	

    For iOS 9+, you will need to disable App Transport Security (ATS). Please refer here for more detail.

    Step 1.7.1: Audience Bidding

    Note: Contact your account manager for Audience Bidding placement setup.

    To use the InMobi Audience Bidding SDK, here is how you can expect the flow to go:

    • The InMobi Audience Bidder SDK will make an ad request and return a bid object
    • The bid object from InMobi Audience Bidder will have an updated MoPub Ad Object and have pricing keywords attached
    • You then call loadAd() on the MoPub ad object as before
    • If InMobi is selected to fill, The InMobi Audience Bidder SDK will handle the rendering

    Optionally, if you would like to handle the keywords yourself, you may also observe the below flow:

    • The InMobi Audience Bidder SDK will make an ad request.
    • The response from InMobi Audience Bidder will have an IMABBidResponse object
    • You may query the object for the bid keyword, price, granular keyword, InMobi placement, and buyer
    • You would then append the bid keyword to MoPub's AdView
    • You would then call loadAd() on the MoPub ad object as before
    • If InMobi is selected to fill, The InMobi Audience Bidder SDK will handle the rendering


    • Option 1: Add the additional following framework file:

    You can find this file in the following directory: dist/network-support/MoPub/

    InMobiABMoPubPlugin.framework
    	

    If you are updating your iOS SDK version from a prior version, ensure that you've updated all of these files. Otherwise, if this is your first time integrating, just ensure that you link these files in your project.

    • Option 2: Update your podfile

    Add the pod “InMobiABMoPubPlugin" to your podfile. If you don't have an existing podfile, please consult the above documentation for podfiles first.

    platform :ios, '9.0'
    target 'APP_NAME' do
          pod ‘InMobiABMoPubPlugin’
    end
    	
    Step 1.7.1.1 Audience Bidding Setup on MoPub

    To enable Audience Bidding, you will need to do 2 things:

    1. Set up the line item to use the specific keywords with pricing and implement the new AerServ + InMobi bidder class.
    2. Update your existing MoPub implementation.
    • Step 1.7.1.1.1 Setting up the MoPub Line Items
    Option 1 (Setting up Line Items Manually)
    1. Click on Orders -> Create Order
    2. Create a new order
      • Give your order a name (ex. Audience_Bidding_Test)
      • Enter in an advertiser name (ex. InMobi)
    3. Line item type
      • Give your line item a name (ex.IMAB_Banner_0.50)
      • Select type: Network Line Item
      • Select Network: Custom SDK network
      • Custom event class:
        • Banner: IMABCustomEventBanner
        • Interstitial: IMABCustomEventInterstitial
      • Custom event data: {}
      • Under "Budget & schedule", please enter the rate that matches what you have set up on your InMobi + AerServ dashboard for your eCPM (ex. 0.50)
    4. Ad unit targeting
      • Select the app and ad unit for your line item
    5. Audience Targeting
      • Enter the keyword in the "Keyword targeting" in this format IMAB:0.00 (ex. IMAB:0.50)
        eCPM Keyword eCPM Keyword
        0.01 IMAB:0.01 5.00 IMAB:5.00
        0.05 IMAB:0.05 6.00 IMAB:6.00
        0.10 IMAB:0.10 7.00 IMAB:7.00
        0.20 IMAB:0.20 8.00 IMAB:8.00
        0.30 IMAB:0.30 9.00 IMAB:9.00
        0.40 IMAB:0.40 10.00 IMAB:10.00
        0.50 IMAB:0.50 11.00 IMAB:11.00
        0.60 IMAB:0.60 12.00 IMAB:12.00
        0.70 IMAB:0.70 13.00 IMAB:13.00
        0.80 IMAB:0.80 14.00 IMAB:14.00
        0.90 IMAB:0.90 15.00 IMAB:15.00
        1.00 IMAB:1.00 16.00 IMAB:16.00
        1.10 IMAB:1.10 17.00 IMAB:17.00
        1.20 IMAB:1.20 18.00 IMAB:18.00
        1.30 IMAB:1.30 19.00 IMAB:19.00
        1.40 IMAB:1.40 20.00 IMAB:20.00
        1.50 IMAB:1.50 21.00 IMAB:21.00
        1.60 IMAB:1.60 22.00 IMAB:22.00
        1.70 IMAB:1.70 23.00 IMAB:23.00
        1.80 IMAB:1.80 24.00 IMAB:24.00
        1.90 IMAB:1.90 25.00 IMAB:25.00
        2.00 IMAB:2.00 26.00 IMAB:26.00
        2.50 IMAB:2.50 27.00 IMAB:27.00
        3.00 IMAB:3.00 28.00 IMAB:28.00
        3.50 IMAB:3.50 29.00 IMAB:29.00
        4.00 IMAB:4.00 30.00 IMAB:30.00
    6. Click "Save"

    Option 2 (Setting up Line Items with an Automated Script

    Add a Chrome extension to your browser.

    1. Login to the MoPub Dashboard
    2. Create your order
    3. Create the first line item under the order
      • Line Item Setup:
        • Type & Priority: Network Line Item
        • Network: Custom SDK Network
        • Custom Event Class:
          • Banner: IMABCustomEventBanner
          • Interstitial: IMABCustomEventInterstitial
        • Example
        • Under the "Audience Targeting" section:
          • Please enter a keyword in this format: IMAB:0.01
          • Example
        • Staying on the current tab, open the extension.
        • Input the order name and the first line item name
        • Click 'Run' to execute
        • Wait for all the line items to be created

    Step 1.7.1.1.2 Technical Integration Details for Audience Bidding

    For Audience Bidding, here are the required changes that you'll need to do in our code:

    • Integration Step 1: Import the InMobi SDK

    The IMAudienceBidder is a part of the SDK and will be able to handle most of the functionality required for audience bidding.

    #import <InMobiSDK/InMobiSDK.h>
    	
    • Integration Step 2: Initialize the MoPub SDK

    Remember to initialize the MoPub SDK. If you don't initialize, your application may not work as intended.

    MPMoPubConfiguration *sdkConfig = [[MPMoPubConfiguration alloc] initWithAdUnitIdForAppInitialization:@"AD_UNIT_ID"];	
    [[MoPub sharedInstance] initializeSdkWithConfiguration:sdkConfig completion:nil]
    	

    Please Note: Make sure that your implementation uses MoPub's init SDK method if you are using a version of MoPub that supports it. You can consult their docs here for more information: https://developers.mopub.com/publishers/ios/initialize/

    • Integration Step 3: Initialize InMobi Audience Bidder

    You MUST initialize the InMobi Audience Bidder before you make an ad request. Typically, the initialization step may take up to 10 seconds. The initialize method will take in your application site ID (from the InMobi platform). If you have problems finding this information, reach out to your account manager.

    [IMAudienceBidder initializeWithAppID:kASAppID andUserConsent:@{ IM_GDPR_CONSENT_AVAILABLE : “TRUE” }];
    	

    Note:
    If you would like for InMobi to handle keywords (thus simplifying your integration), follow the below steps for Option A.
    If you would like to handle the keywords yourself instead, you may instead follow the steps for Option B. In addition, you will have to call setLocalExtras on the MoPub ad view.

    • Integration Step 4: Create or Submit a Bid

    For Option A, to easily support banner refresh and support subsequent ad requests to the InMobi Audience Bidder, we have a BidObject that you should use. The IMAudienceBidder methods will return a BidObject which you can then call our refreshBid on.

    The +createBidForAdType: method will return a bidObject which you should retain a strong reference to.

    @property (strong, nonatomic) IMBidObject *bidObject;
    	

    For Option B, you will not be able to use the BidObject, and you will have to repeatedly call the + submitBidForAdType: method.

      • Option A: Make an ad request using the bid object
        • The +createBidForAdType method requires for you to pass in an adType, InMobi placement (PLC), MoPub Ad View, and delegate. Contact your InMobi account manager if you have any questions about this.
        • The adType ENUM: kIMBiddingAdTypeBanner, kIMBiddingAdTypeInterstitial
        • The setBannerSlotSize:adSize method will use to set the banner size. By default banner size will be 320*50.
        • The +submitBid method will kick off the bidding process with the created bid object. You may review IMAudienceBidder.h for more information.
      • Option B: Submit a bid request using submitBidForAdType
        • The +submitBidForAdType method requires for you to pass in an adType, InMobi placement (PLC), and delegate. Contact your InMobi account manager if you have any questions about this.
        • The adType ENUM: kIMBiddingAdTypeBanner, kIMBiddingAdTypeInterstitial
        • The +submitBidForAdType method also will kick off the bidding process (no need to call +submitBid seperately).You may review IMAudienceBidder.h for more information.

    A full example snippet for banner and interstitial is available below.

    Banner Code Examples

    Option A: InMobi will handle the keywords for you in this snippet.

    self.adView = [[MPAdView alloc] initWithAdUnitId:MP_BANNERID size:MOPUB_BANNER_SIZE];
    
    self.adView.frame = CGRectMake((self.view.bounds.size.width - MOPUB_BANNER_SIZE.width) / 2, self.view.bounds.size.height - (MOPUB_BANNER_SIZE.height), MOPUB_BANNER_SIZE.width,MOPUB_BANNER_SIZE.height);
    
    [self.view addSubview:self.adView];
    
    self.adView.delegate = self;
    
    // Call createBidForAdType and retain a reference to the bid object to be utilized later
    self.bannerBidObject = [IMAudienceBidder createBidForAdType:kIMBiddingAdTypeBanner withPlacement:AS_BannerID_AB adObj:self.adView andDelegate:self];
    
    // Set the banner ad size
    [self.bannerBidObject setBannerSlotSize:MOPUB_BANNER_SIZE];
    
    // Submit the bid to kick off the bidding process
    [self.bannerBidObject submitBid];
    	

    Option B: You will handle the keywords in this example. Call submitBidForAdType and do not use a bid object.

    self.adView = [[MPAdView alloc] initWithAdUnitId:MP_BANNERID size:MOPUB_BANNER_SIZE];
    
    self.adView.frame = CGRectMake((self.view.bounds.size.width - MOPUB_BANNER_SIZE.width) / 2, self.view.bounds.size.height - (MOPUB_BANNER_SIZE.height), MOPUB_BANNER_SIZE.width,MOPUB_BANNER_SIZE.height);
    
    [self.view addSubview:self.adView];
    
    self.adView.delegate = self;
    
    // Call submitBidForAdType if you plan to add keywords to the object yourself
    [IMAudienceBidder submitBidForAdType:kIMBiddingAdTypeBanner withPlacement:AS_BannerID_ABadSize:MOPUB_BANNER_SIZE andDelegate:self];
    	

    Remember to add the banner to the view and call show on it once you get the bidReceived delegate callback. For more information about MoPub banner implementation, you can consult the relevant MoPub documentation here: https://developers.mopub.com/docs/ios/banner/

    Interstitial Code Examples

    Option A: InMobi will handle the keywords for you in this snippet.

    self.interstitial = [MPInterstitialAdControllerinterstitialAdControllerForAdUnitId:MP_INTERSTITIALID];
    
    self.interstitial.delegate = self;
    
    // Call createBidForAdType and retain a reference to the bid object to be utilized later
    self.interstitialBidOBject = [IMAudienceBiddercreateBidForAdType:kIMBiddingAdTypeInterstitial withPlacement:AS_InterstitialID_ABadObj:self.interstitial andDelegate:self];
    
    // Submit the bid to kick off the bidding process
    [self.interstitialBidOBject submitBid];
    	

    Option B: You will handle the keywords in this example. Call submitBidForAdType and do not use a bid object.

    self.interstitial = [MPInterstitialAdControllerinterstitialAdControllerForAdUnitId:MP_INTERSTITIALID];
    self.interstitial.delegate = self;
    
    // Call submitBidForAdType if you plan to add keywords to the object yourself
    [IMAudienceBidder submitBidForAdType:kIMBiddingAdTypeInterstitial withPlacement:AS_InterstitialID_AB andDelegate:self];
    	

    Remember to then call load on the interstitial once you get the bidReceived delegate callback. You can reference the section below as well to see an example. For more information about MoPub interstitial implementation, you can consult the relevant MoPub documentation here: https://developers.mopub.com/docs/ios/interstitial/

    Also, do remember to call show when the interstitial has loaded! (when you get the interstitialDidLoadAd delegate callback from MoPub)


    • Integration Step 5: Implement the IMAudienceBidderDelegate Interface

    Option A: The IMAudienceBidderDelegate has 2 methods that need to be implemented:

    • -audienceBidderDidReceiveBidFor:
    • -audienceBidderDidFailBidFor:

    In either scenario (banner or interstitial), you will be returned a MPAdView for banner or MPInterstitialAdController for interstitial. If a bid was returned from createBidForAdType, you would then be given an updated MoPub Ad object. If a bid was not returned from createBidForAdType, you get returned a reference of the MoPub ad object with unmodified keywords. Below is an example delegate implementation covering both banner and interstitial:

    // Use a Boolean to keep track so you don't call loadAd on the banner repeatedly. 
    Boolean bannerLoaded = false;
    
    - (void)audienceBidderDidFailBidFor:(id)adObject withError:(NSError *error {
    
      // If the returned and updated adObject is a banner:
      if([adObject isKindOfClass:[MPAdView class]]) {
    
          // If the banner has not yet been loaded, call loadAd on the updated ad view
          if (!bannerLoaded){
              [self.adView loadAd];
          }
      }
      // If the returned adObject is an interstitial:
      else if([adObject isKindOfClass:[MPInterstitialAdController class]]) {
          [adObject loadAd];
      }
    }
    - (void)audienceBidderDidReceiveBidFor:(id)adObject {
    
      // If the returned and updated adObject is a banner:
      if([adObject isKindOfClass:[MPAdView class]]) {
    
          // If the banner has not yet been loaded, call loadAd on the updated MoPub Ad View
          if (!bannerLoaded){
              [adObject loadAd];
          }
      }
      // If the returned adObject is an interstitial:
      else if([adObject isKindOfClass:[MPInterstitialAdController class]]) {
          [adObject loadAd];
      }
    }
    	

    Option B: If you prefer to handle keywords yourself, the IMAudienceBidderDelegate has 2 methods that need to be implemented:

    • -audienceBidderDidGenerateBidResponse:
    • -audienceBidderDidFailBidFor:

    For this method, you will have to set the kIMABLocalCacheKey in the localExtras of the respective adview / interstitial. In addition, you may be returned a IMBidResponse object. You may access the follow properties on the object:

    • NSString* placement - A NSString that describes the InMobi placement
    • NSString* buyer - A NSString that describes the buyer
    • NSNumber* price - A NSNumber that describes the price
    • NSString* keyword - A NSString that describes a keyword that should be provided to the MoPub ad object
    • NSString* higherGranularityKeyword - A NSString that describes a granular keyword

    In either scenario (banner or interstitial), if a bid was returned from submitBidForAdType, you would then be given a IMBidResponse object. If a bid was not returned from submitBidForAdType, you do not get returned an IMBidResponse object and you can choose to add additional keywords at this step and/or call loadAd. Below is an example delegate implementation covering both banner and interstitial:

    // Use a Boolean to keep track so you don't call loadAd on the banner repeatedly. 
    Boolean bannerLoaded = false;
    
    - (void)audienceBidderDidGenerateBidResponse:(IMBidResponse *)bidResponse {
    
      // If the bid response placement is a banner
      if (bidResponse.placement == AS_BannerID_AB) {
    
          // Set or append the returned InMobi bidResponse keywords on the adView
          [self.adView setKeywords:bidResponse.keyword];
    
          // Set the local extras of the adview
          self.adView.localExtras = @{kIMABLocalCacheKey : bidResponse.placement};
    
          // If the banner has not yet been loaded, call loadAd on the updated MPAdView
          if (!bannerLoaded){
              [self.adView loadAd];
          }
      } else if (bidResponse.placement == AS_InterstitialID_AB) {
    
          // Set or append the returned InMobi bidResponse keywords on the interstitial
          [self.interstitial setKeywords:bidResponse.keyword];
    
          // Set the local extras of the interstitial
          self.interstitial.localExtras = @{kIMABLocalCacheKey : bidResponse.placement};
    
          [self.interstitial loadAd];
      }
    }
    	

    • Integration Step 6: Implement Banner Callbacks to Support Banner Refresh with a New Bid

    We support MoPub's automatic banner refresh in the InMobi Audience Bidder SDK for both implementation options, A and B.

    Option A: You'll need to include an +submitBid method call in the MoPub adViewDidLoadAd / adViewDidFailToLoadAd delegate callbacks. This will allow us to provide a fresh bid each time the banner is refreshed.

    Note: The submitBid method should only be called after the banner bid object has been constructed to avoid unexpected behavior.

    - (void)adViewDidLoadAd:(MPAdView *)view {
    
    // Ensure that you do not call loadAd again on the MoPub Ad View
    bannerLoaded = true;
    
    // On a successful load, call submitBid for the next refresh
    [self.bannerBidObject submitBid];
    }
    - (void)adViewDidFailToLoadAd:(MPAdView *)view {
    
    // Ensure that you do not call loadAd again on the MoPub Ad View
    bannerLoaded = true;
    
    // On a failed load, still call submitBid for the next banner refresh
    [self.bannerBidObject submitBid];
    }
    	

    Option B: You'll need to include a new +submitBidForAdType method call in the MoPub adViewDidLoadAd / adViewDidFailToLoadAd delegate callbacks. This will allow us to provide a fresh bid each time the banner is refreshed.

    - (void)adViewDidLoadAd:(MPAdView *)view {
    
    // Ensure that we do not call loadAd again on the MPAdView
    bannerLoaded = true;
    
    // On a successful load, do a new submitBidForAdType for the next refresh
    [IMAudienceBidder submitBidForAdType:kIMBiddingAdTypeBanner withPlacement:AS_BannerID_AB adSize:MOPUB_BANNER_SIZE andDelegate:self];
    }
    - (void)adViewDidFailToLoadAd:(MPAdView *)view {
    
    // Ensure that we do not call loadAd again on the MPAdView
    bannerLoaded = true;
    
    // On a failed load, still call submitBidForAdType for the next banner refresh
    [IMAudienceBidder submitBidForAdType:kIMBiddingAdTypeBanner withPlacement:AS_BannerID_AB adSize:MOPUB_BANNER_SIZE andDelegate:self];     
    }
    	
    • Integration Step 7: Get a New Interstitial Bid

    Option A: After an interstitial is shown, you can optionally call 'submitBid' on the interstitial bid object to get a new bid from the InMobi Audience Bidder.

    Note: The submitBid method should only be called after the interstitial bid object has been constructed to avoid unexpected behavior.

    [self.interstitialBidOBject submitBid];
    	

    Option B: After an interstitial is shown, you can optionally call 'submitBidForAdType' on to get a new bid from the InMobi Audience Bidder.

    [IMAudienceBidder submitBidForAdType:kIMBiddingAdTypeInterstitial withPlacement:AS_InterstitialID_AB andDelegate:self];
    	
    • Step 1.7.1.1.3: Testing your Audience Bidding Integration

    In order to test your Audience Bidding implementation, you will need to:

    • Make sure you enable test mode on your placement through the UI
    • Set up a line item with
      • CPM 0.00
      • Keyword: IMAB:0.00
    • Two ways to verify:
      • Through Charles:
        • In the ad request we send to Mopub (ads.mopub.com/m/ad), check:
        • Under "Contents" & "JSON Text", you should see a key value pair of: "q: keywords, testing, IMAB:0.00"
      • Through Mopub Reporting:
        • Make sure the ad filled on testing
        • Make sure the numbers align for the newly generated line item at $0.00 (it might take a few minutes for Mopub to report it).

    Step 1.7.2: Non-audience Bidding

    • Step 1.7.2.1: Add the MoPub to AerServ Adapter
      • Add the following files from dist/network-support/MoPub/AerServCustomEvents to your project:
        • network-support/MoPub/AerServCustomEvents/AerServBidListener.h
        • network-support/MoPub/AerServCustomEvents/AerServBidObject.h
        • network-support/MoPub/AerServCustomEvents/AerServBidObject.m
        • network-support/MoPub/AerServCustomEvents/AerServBidder.h
        • network-support/MoPub/AerServCustomEvents/AerServBidder.m
        • network-support/MoPub/AerServCustomEvents/AerServCustomEventBanner.m
        • network-support/MoPub/AerServCustomEvents/AerServCustomEventInterstitial.m
        • network-support/MoPub/AerServCustomEvents/AerServCustomEventRewardedInterstitial.m
    • Step 1.7.2.2: Configure Ad Setting on MoPub Dashboard
      1. (Optional) Create a new AdUnit with the ad type that you'll like to use AerServ with. You can use an existing AdUnit if one already exists.
      2. Now go to the 'Orders' tab and click on Create order. Creating a new 'Order' is optional. You can use an existing order if one already exists. If you decide to use an existing order, you will need to create a new Line Item instead.
      3. When creating a new Order/ Line Item, use the following parameters:
        • Advertiser: AerServ
        • Type & Priority: Network
        • Network: Custom Native Network
        • Class: Use one of the following class name
          • For banner: AerServCustomEventBanner
          • For interstitial: AerServCustomEventInterstitial
          • For rewarded video: AerServCustomEventRewardedInterstitial
        • eCPM: You will need to use the eCPM from the AerServ dashboard. If you have any questions please contact our support.
        • Data: AerServ ad parameters, in JSON format. This field will take any additional parameters for the AerServ SDK. Refer to Advance Topics - Server Parameters for more information.
        • Select the newly created AdUnit created or use existing a AdUnit
    • Step 1.7.2.3: AerServ Ad Parameter
      AerServ server ad parameters that you entered on MoPub's web interface must be in JSON format. Currently we support these parameters:
      NAME TYPE REQUIRED DEFAULT DESCRIPTION
      placement String Yes N/A AerServ Placement
      Sample AerServ Ad Parameter
      {"placement": "1000741"}
      		
    • Step 1.7.2.4: Event Mapping

      AerServ banner events are mapped to MoPub's MPAdViewDelegate events, as follows:

      • -adViewDidLoadAd:-bannerCustomEvent:didLoadAd:
      • -adViewDidFailToLoadAd:withError:-bannerCustomEvent:didFailToLoadAdWithError:
      • -willLeaveApplicatonFromAd:-bannerCustomEventWillLeaveApplication:
      • -adWasClicked:-bannerCustomEventWillBeginAction:
      • -didDismissModalViewForAd:-bannerCustomEventDidFinishAction:

      AerServ interstitial events are mapped to MoPub's MPInterstitialAdControllerDelegate events, as follows:

      • -interstitialViewControllerDidPreloadAd:-interstitialCustomEvent:didLoadAd:
      • -interstitialViewControllerAdFailedToLoad:withError:-interstitialCustomEvent:didFailToLoadAdWithError:
      • -interstitialViewControllerWillDisappear:-interstitialCustomEventWillDisappear:
      • -interstitialViewControllerDidDisappear:-interstitialCustomEventDidDisappear:
      • -interstitialViewControllerWillAppear:-interstitialCustomEventWillAppear:
      • -interstitialViewControllerDidAppear:-interstitialCustomEventDidAppear:
      • -interstitialViewControllerAdWasTouched-interstitialCustomEventDidReceiveTapEvent:

      AerServ rewarded video events are mapped to MoPub's MPRewardedVideoAdManagerDelegate events, as follows:

      • -interstitialViewControllerDidPreloadAd-rewardedVideoDidLoadAdForCustomEvent:
      • -interstitialViewControllerAdFailedToLoad:withError:-rewardedVideoDidFailToLoadAdForCustomEvent:error:
      • -interstitialViewControllerWillDisappear: → -rewardedVideoWillDisappearForCustomEvent
      • -interstitialViewControllerDidDisappear:-rewardedVideoDidAppearForCustomEvent:
      • -interstitialViewControllerWillDisappear:-rewardedVideoWillAppearForCustomEvent:
      • -interstitialViewControllerDidAppear:-rewardedVideoWillAppearForCustomEvent:
      • -interstitialViewControllerAdWasTouched:-rewardedVideoDidReceiveTapEventForCustomEvent:
      • -interstitialViewControllerDidVirtualCurrencyReward:vcData:-rewardedVideoShouldRewardUserForCustomEvent:reward:

    Step 2: Additional Settings

    • Step 2.1: Disabling App Transport Security for iOS 9+

      Select your application's Info.plist, right-click on it and open as source code. Copy the following code into your Info.plist's xml.

      <key>NSAppTransportSecurity</key>
      <dict>
        <key>NSAllowsArbitraryLoads</key> <true/>
      </dict>
      		
    • Step 2.2: iOS 12 Wifi Settings

      Step 2.2.1: Enable XCode WiFi Settings

      From iOS 12 onwards, Apple has introduced privacy settings to access WiFi details. If the publisher decides to share wifi details, they can take advantage of targeted ads. Benefits of ad targeting are that, the ads are more useful and meaningful to users.

      How to enable Access Wifi Information

      1. Enable access WiFi information feature to your App ID.

      2. Enable access WiFi information feature for your target app from XCode capabilities.

      3. WiFi Access should get added to your App.entitlements file. If not please add the following code to your App.entitlements file.
        <dict>
            <key>com.apple.developer.networking.wifi-info</key>
            <true/>
        </dict>
        			

    • Step 2.2.2: AVAudioSession event changes in WKWebView

      WKWebView ignores AVAudioSessionCategory, Publisher can handle audio interruptions by registering to observe AVAudioSessionInterruptionnotification posted by AVAudioSession. Publisher should ensure minimum possible disruption, and the most graceful possible recovery, from the perspective of the user.


    • Step 2.2.3: Observing Audio Interruptions

      To handle audio interruptions, begin by registering to observe notifications of type AVAudioSessionInterruptionNotification.


    • - (void)registerForAudioInterruptionNotification {
      
          AVAudioSession *audioSession = [AVAudioSession sharedInstance];
          [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleAudioSessionInterruption:) name:AVAudioSessionInterruptionNotification object:audioSession];
      }
      - (void)handleAudioSessionInterruption:(NSNotification *)notification {
      
          NSNumber *interruptionType = [[notification userInfo] objectForKey:AVAudioSessionInterruptionTypeKey];
      
          NSNumber *interruptionOption = [[notification userInfo] objectForKey:AVAudioSessionInterruptionOptionKey];
          switch (interruptionType.unsignedIntegerValue) {
      
              case AVAudioSessionInterruptionTypeBegan: {
                  /* the system has interrupted your audio session */
                  /* Pause, Save State, Update UI */
                  break;
              }
              case AVAudioSessionInterruptionTypeEnded: {
                  if (interruptionOption && interruptionOption.unsignedIntegerValue == AVAudioSessionInterruptionOptionShouldResume) {
                      /* the interruption has ended */
                      /* Resume, Update State, Update UI */
                  }
                  break;
              }
          }
      }
      		

      The posted NSNotification instance contains a userInfo dictionary providing the details of the interruption. You can determine the type of interruption by retrieving the AVAudioSessionInterruptionType value from the userInfo dictionary. The interruption type indicates whether the interruption has begun or has ended. If the interruption type is AVAudioSessionInterruptionTypeEnded, the userInfo dictionary might contain an AVAudioSessionInterruptionOptions value. An options value of AVAudioSessionInterruptionOptionShouldResume is a hint that indicates whether your app should automatically resume playback if it had been playing when it was interrupted. Media playback apps should always look for this flag before beginning playback after an interruption. If it’s not present, playback should not begin again until initiated by the user. Apps that don’t present a playback interface, such as a game, can ignore this flag and reactivate and resume playback when the interruption ends.

    Note: Please note that there is no guarantee that a begin interruption will have a corresponding end interruption. Your app needs to be aware of a switch to a foreground running state or the user pressing a Play button. In either case, determine whether your app should reactivate its audio session.

    For more details, please refer to the following:

    1. https://developer.apple.com/documentation/avfoundation/avaudiosession/1616596-interruptionnotification
    2. https://developer.apple.com/library/archive/documentation/Audio/Conceptual/AudioSessionProgrammingGuide/HandlingAudioInterruptions/HandlingAudioInterruptions.html

    Version History

    SDK 9.0

    • 9.0.0: 9/20/19

      - Changes to support iOS 13

      - New and improved Modularised SDK design

      - Add InMobiMediationSDK.framework to your project for AerServ Mediation.

      - Addressing issue with layering of FAN banners upon refresh

      - SKStoreProductViewController crash fix.

      - Removed Support for iOS 8.

      - Removed Support for AerServ Native ad format.

      - Removed UIWebView from InMobi SDK. Viewability Partners might be using it.

      - Size reduction for both Framework and ipa inflation.

      - Various Bug Fixes and performance improvements

      - Adapter updates for the following mediation partners:

      • MoPub - v5.9.0
      • Google Mobile Ads - v7.50.0

      - APIs Added

      • IMBanner Class

        + -(void)cancel;

      • IMInterstitial Class

        + -(void)cancel;

      - APIs Removed
      • ASAdView Class

        - @property (nonatomic, assign) ASEnvironmentType env;

        - @property (nonatomic, assign) ASPlatformType platform;

        - @property (nonatomic, assign) BOOL isMuted;

        - @property (nonatomic, assign) BOOL outlineAd;

        - @property (nonatomic, assign) BOOL sizeAdToFit;

        - @property (nonatomic, assign) BOOL useHeaderBidding;

        - @property (nonatomic, strong) NSArray* keyWords;

        - @property (nonatomic, assign) BOOL allowAdvertiserCloseButton;

        - -(void)forceRefreshAd;

        - -(CGSize)adContentSize;

        - -(void)rotateToOrientation:(UIInterfaceOrientation)newOrientation;

        - -(void)play;

        - -(void)pause;


      • ASAdViewDelegate Protocol

        - -(void)willLeaveApplicatonFromAd:(ASAdView*)adView;

        - -(void)adSizeChanged:(ASAdView*)adView;

        - -(void)adView:(ASAdView*)adView didFireAdvertiserEventWithMessage:(NSString*)msg;


      • ASInterstitialViewController Class

        - @property (nonatomic, assign) ASEnvironmentType env;

        - @property (nonatomic, assign) ASPlatformType platform;

        - @property (nonatomic, assign) BOOL isMuted;

        - @property (nonatomic, assign) BOOL showOutline;

        - @property (nonatomic, assign) BOOL useHeaderBidding;

        - -(void)play;

        - -(void)pause;


      • ASInterstitialViewControllerDelegate Protocol

        - -(void)interstitialViewControllerAdInteraction:(ASInterstitialViewController*)viewController;

        - -(void)interstitialViewController:(ASInterstitialViewController*)viewController didFireAdvertiserEventWithMessage:(NSString*)msg;

      • 8.2.0: 8/5/19
        • Chrome Custom tabs support
        • Thread Optimizations
        • Bug Fixes for SDK and AudienceBidder Plugin
      • 8.1.2: 7/18/19
        • Size reduction
        • Support for Audience Bidding for DFP
        • New api to set slot size for Banner in Audience Bidding
      • 8.1.1: 6/19/19
        • Updated AdColony SDK support to 3.3.10
        • Updated Audience Network (Facebook) support to 5.3.1
      • 8.1.0: 5/14/19
        • DFP Plugin Support
        • Mopub Audience Bidding Plugin Keyword Handling
        • Bug fixes
      • 8.0.8: 4/17/19
        • Bug Fixes
      • 8.0.7: 4/05/19
        • Additional support for higher granularity keywords
      • 8.0.5: 3/11/19
        • Audience Bidder for the Mopub Plugin
        • Telaria Adapter Deprecation
        • Flurry Banner Adapter Deprecation
        • Applovin 3rd Party API Reporting updates
        • Chartboost 3rd Party API Reporting updates
        • Mediated SDK updates
        • Bug Fixes
      • 8.0.2: 12/13/18
        • Mediation bug Fixes
      • 8.0.1: 11/28/18
        • Unified InMobi + AerServ SDK

    exchange | Audience Bidding for DFP (Android)

    Prerequisites

    Make sure that your Android application meets the following requirements before proceeding.

    • Android 4.2.2 (Jelly Bean, API 17) and higher. MRAID ads require API 19 and higher.
      Older Android versions may work, but are not officially supported.
    • Google Play Services will adhere to the user’s ad tracking preferences. For more information, please see Google's website regarding their Advertising ID.

    Note: If you are using Android Studio 3.0+, you'll need to disable AAPT 2.0. To do this, you'll need to add the following to your gradle.properties:

    android.enableAapt2=false
    	

    Step 1: Integrating the SDK

    Step 1.1: Adding the libraries

    Option 1: Pulling the Latest SDK via JCenter

    If you are using Gradle to build your Android applications, you can pull the latest version of the SDK from JCenter as described below:

    1. Include JCenter in your top-level build.gradle file
      allprojects {
          repositories {
             jcenter()
          }
      }
      		
    2. Add the following line to the dependencies element in your application module’s build.gradle file.

      For Non-Audience Bidder:

      implementation 'com.inmobi.monetization:inmobi-mediation:9.0.0'
      		

      For Audience Bidder:

      implementation 'com.inmobi.monetization:inmobi-AB-plugin-dfp:1.0.1'
      		
    3. Sync your Gradle project to ensure that the dependency is downloaded by the build system.

    Option 2: Adding the SDK Library to your Application Project

    Alternately, you can download the latest version of InMobi’s SDK here and copy the library to your application module’s libs/ directory.

    Add the following files to the app/lib folder within your project.

    libs/InMobiSDK.aar
    libs/InMobiMediationSDK.aar
    	

    In case you’re integrating with InMobi Audience Bidding solution, you'll need an additional aar file (InMobiABDFPPlugin-x.x.x.aar).

    These resources can all be found in the download along with the InMobi SDK.

    To add the library to your project’s dependencies, add this line to the dependencies element in your module’s build.gradle:

    implementation fileTree(dir: 'libs', include: ['*.aar])
    	

    The SDK bundle contains all media adapters that we support. Prune the downloaded folder to retain the media adapters you need.

    Warning: Please remove all older versions of the InMobi SDK (8.X.X and older) and all older versions of the AerServ SDK. Otherwise, your code will not compile! Please reach out to your account manager if you have any questions.

    Please note that using any other version of these SDKs may cause issues and unintended behavior.

    Step 1.2: Gradle settings

    You'll need to add the following settings to your application's build.gradle:

    android {
      defaultConfig { 
      }
      buildTypes {
        ...
      }
      sourceSets {
        main {
        }
      }
    }
    repositories {
      ...
    }
    dependencies {
    
      implementation 'com.google.android.gms:play-services-ads-identifier:16.0.0'
      implementation 'com.google.android.gms:play-services-basement:16.1.0'
      implementation 'com.google.android.gms:play-services-location:16.0.0'
      implementation 'com.squareup.picasso:picasso:2.71828'
    }
    	

    Step 1.3: Android Manifest

    Add the following Android permission into your Android Manifest:

    <?xml version='1.0' encoding='utf-8'?>
    <manifest xmlns:android='http://schemas.android.com/apk/res/android'  
      package='com.sample.myapp' >
    
      <!-- Required Permissions -->
      <uses-permission android:name="android.permission.INTERNET" />
    
      <!-- Optional Permissions -->
      <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
      <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
      <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
      <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    
      <application
        android:allowBackup='true'
        android:label='@string/app_name'>
      </application>  
    </manifest>
    	

    Note: Not including the optional permission MAY negatively impact fill for the respective networks that use these permissions.

    Important Prerequisites

    • Checkpoint 1: Preparing Your App for Android 10

      InMobi SDK is compatible with Android 10 (API level 29), the latest version of the Android platform. On Android P onwards, apps make connections over HTTPS by default. Though InMobi supports the adoption of HTTPS, the current setup requires our demand partners to support HTTPS as well. The publisher can change their settings to HTTP if it has an impact on the revenue potential.

    • Checkpoint 2: Preparing Your App for AndroidX

      InMobi SDK is compatible with AndroidX (JetPack) library. In case your app uses the AndroidX library, then follow the standard guidelines by Google for migration by adding both the flags in build file.

      android.useAndroidX=true
      android.enableJetifier=true
      		

    Note: It is highly recommended to upgrade Android Gradle plugin version to 4.1 or greater to avoid known issues in the jetifier which is fixed in the latest Gradle plugin version. To upgrade Android gradle plugin version please refer to Android developer documentation.

    Step 1.4: Integrating DFP to InMobi Adapter

    Step 1.4.1: Audience Bidding

    To use the InMobi Audience Bidding SDK, here is how you can expect the flow to go:

    1. The InMobi Audience Bidder SDK will make an ad request and return a bid token
    2. The bid token from the ad network will have an updated PublisherAdRequest.Builder object and have pricing keywords attached
    3. You then call loadAd() on the DFP ad object as before.
    4. If InMobi is selected to fill, The InMobi Audience Bidder SDK will handle the rendering

    Note: Contact your account manager for Audience Bidding placement setup.

    Optionally, if you would like to handle the keywords yourself, you may also observe the below flow:

    1. The InMobi Audience Bidder SDK will make an ad request and return a bid token
    2. The bid token from the ad network will have an IMABBidResponse object
    3. You may query the object for the bid keyword, price, granular keyword, InMobi placement, and buyer
    4. You would then append the bid keyword to PublisherAdRequest.Builder
    5. You would then call loadAd() on the DFP ad object as before
    6. If InMobi is selected to fill, The InMobi Audience Bidder SDK will handle the rendering
    Step 1.4.1.1: Enabling Audience Bidding Setup on DFP

    To enable Audience Bidding, you will need to do 2 things:

    1. Set up the yield group to use the specific keywords with pricing used by the IMAudienceBidder class.
    2. Update your existing DFP integration details.
    Step 1.4.1.1.1: Setting Up the DFP Yield Groups
    1. Sign in to Google Ad Manager.
    2. Click Delivery > Yield groups.
    3. Click New Yield Group. Enter a unique name for the yield group that describes the reporting process.
    4. Select the Ad format and Inventory type you wish to target with this yield group.
    5. Under Inventory > Key-Values:, Define the Key values using the keyword: “IMAB” for different price points.

      Enter the keyword in the following format IMAB:0.00 (eg. IMAB:0.50)

    6. Add/map the ad units to these keywords under Custom Targeting.

    7. Ad Exchange will be your default partner/demand source on the UI. Proceed to add additional third-party yield partner and select InMobi (as the ad network) to compete for the targeted inventory.

      Note: Please ensure that the CustomClass name is as follows for Banner and Interstitial
      Banner: com.inmobi.plugin.dfp.IMABCustomEventBanner
      Interstitial: com.inmobi.plugin.dfp.IMABCustomEventInterstitial

    8. Click Save to confirm your changes without activating this yield group for delivery. Conversely, click Save and Activate to confirm your changes and immediately approve this yield group for delivery.
    9. Once a yield group has been created and activated, Ad Manager is ready to begin using the yield group to fill requests.
    10. Note: The different recommended price points are shown below in this step:

      Banner Price Points

      Enter the keyword in the "Keyword targeting" in the following format IMAB:0.00 (ex. IMAB:0.50)

      eCPM

      Keyword

      eCPM

      Keyword

      <0.05

      IMAB:0.05

      1

      IMAB:1.00

      0.1

      IMAB:0.10

      1.2

      IMAB:1.20

      0.2

      IMAB:0.20

      1.4

      IMAB:1.40

      0.3

      IMAB:0.30

      1.6

      IMAB:1.60

      0.4

      IMAB:0.40

      1.8

      IMAB:1.80

      0.5

      IMAB:0.50

      2

      IMAB:2.00

      0.6

      IMAB:0.60

      2.5

      IMAB:2.50

      0.7

      IMAB:0.70

      3

      IMAB:3.00

      0.8

      IMAB:0.80

      3.5

      IMAB:3.50

      0.9

      IMAB:0.90

      >4.00

      IMAB:4.00


      Interstitial Price Points

      eCPM

      Keyword

      eCPM

      Keyword

      <0.50

      IMAB:0.50

      7

      IMAB:7.00

      1

      IMAB:1.00

      8

      IMAB:8.00

      1.5

      IMAB:1.50

      9

      IMAB:9.00

      2

      IMAB:2.00

      10

      IMAB:10.00

      2.5

      IMAB:2.50

      12

      IMAB:12.00

      3

      IMAB:3.00

      14

      IMAB:14.00

      3.5

      IMAB:3.50

      16

      IMAB:16.00

      4

      IMAB:4.00

      18

      IMAB:18.00

      4.5

      IMAB:4.50

      20

      IMAB:20.00

      5

      IMAB:5.00

      22

      IMAB:22.00

      6

      IMAB:6.00

      >24.00

      IMAB:24.00

    Step 1.4.1.1.2: Updating Integration Details for Audience Bidding

    For Audience Bidding, here are the required changes that you'll need to do in our code:

    1. Integration Step 1: Add additional imports

      Our IMAudienceBidder will have most the necessary classes you'll need for working with our bidder.

      import com.inmobi.plugin.dfp.IMAudienceBidder;
      import com.inmobi.ads.InMobiAudienceBidder;
      		

    2. Integration Step 2: Initialize the InMobi Audience Bidder

      You MUST initialize the InMobi Audience Bidder before you make an ad request. Typically, the initialization step may take up to 10 seconds. The initialize method will take in the current context and your application site ID (from the InMobi platform). If you have problems finding this information, reach out to your account manager.

      InMobiAudienceBidder.initialize(this, IMAB_SITE_ID);
      		

      You may also initialize the InMobi Audience Bidder SDK with a GDPR consent object.

      JSONObject consentObject = new JSONObject();
      
      try {consentObject.put("gdpr_consent_available", true);
      }
      catch (JSONException e) {
      
      // Error handling here
      }
      
      InMobiAudienceBidder.initialize(this, IMAB_SITE_ID, consentObject);
      		

    3. Integration Step 3: Get the singleton instance of the IMAudienceBidder

      Our IMAudienceBidder class will power the majority of the bidding functionality.

      IMAudienceBidder inMobiAudienceBidder = IMAudienceBidder.getInstance();
      		

    4. Integration Step 4: Create a BidToken for later

      To easily support banner refresh and subsequent ad requests for the InMobi Audience Bidder, InMobi provides a BidToken that you may use. InMobi recommends retaining a reference to this. Our bid methods will return this BidToken which you can then call our refreshBid on. Our bid token constructor will require you to pass in an InMobi placement (PLC). Contact your InMobi account manager if you have any questions about this.

      private IMAudienceBidder.BidToken bidToken;
      		

    5. Integration Step 5: Make an Ad request using the BidToken

      This step can be broken down into a couple smaller parts. Full example snippets for banner and interstitial are available below.

      1. Create a PublisherAdRequest.Builder object and ensure build is not called on this object.
      2. The banner bidder has a constructor method that will accept the current context, InMobi banner placement, PublisherAdRequest.Builder, and a listener ( IMAudienceBidderBannerListener)
      3. The interstitial bidder has a constructor method that will accept the current context, InMobi interstitial placement, PublisherAdRequest.Builder, and a listener( IMAudienceBidderInterstitialListener)
      4. You may define multiple bidTokens.
      5. Both banner and interstitial listeners will define onBidReceived and onBidFailed callback methods that must be implemented.
    6. Option A:

      If you would like for InMobi to handle the keywords (thus simplifying your integration), implement the IMAudienceBidderBannerListener or IMAudienceBidderInterstitialListener interface

      1. For onBidReceived (meaning a bid was received from the InMobi Audience Bidder), you get returned an updated PublisherAdRequest.Builder object. Following this, you have to call build() on this updated object. Finally, use PublisherAdRequest object to call loadAd() on DFP ad object.
      2. For onBidFailed (meaning InMobi Audience Bidder failed to give a bid), you get returned a reference of the PublisherAdRequest.Builder object with unmodified keywords. You then may call loadAd() on this DFP ad object.

      Banner Code Examples

        // Use a Boolean to keep track so we don't call loadAd() on the banner repeatedly.
        public Boolean bannerLoaded = false;
      
        bannerBidToken = inMobiAudienceBidder.createBidToken(this, AB_BannerPLC, builder, dipViewWidth, dipViewHeight, new IMAudienceBidder.IMAudienceBidderBannerListener()
        {
      
      @Override public void onBidReceived(@NonNull final PublisherAdRequest.Builder adRequestBuilder)
        {
      
        // Bid was received from InMobi Audience Bidder. Call loadAd() on the updated ad object.
      
        // If the banner has not yet been loaded, call loadAd() to load the ad into the view
      
        if (!bannerLoaded) {
        PublisherAdRequest publisherAdRequest = adRequestBuilder.build();
      
        mPublisherAdView.loadAd(publisherAdRequest);
      }
        @Override public void onBidFailed(@NonNull PublisherAdRequest.Builder adRequestBuilder, @NonNull final Error error)
        {
      
        // No Bid received from InMobi Audience Bidder. Call loadAd() on the ad object.
      
        // If the banner has not yet been loaded, call loadAd() on the updated ad view
      
        if (!bannerLoaded) {
        PublisherAdRequest publisherAdRequest = adRequestBuilder.build();
      
        mPublisherAdView.loadAd(publisherAdRequest);
        }
        }
        });
      
        // Call update bid to start this process bannerBidToken.updateBid();
        });
      	

      Interstitial Code Examples

        interstitialBidToken = inMobiAudienceBidder.createBidToken(Activity.this, AB_InterstitialPLC, adRequestBuilder, new IMAudienceBidder.IMAudienceBidderInterstitialListener()
        {
      
      @Override public void onBidReceived(@NonNull final PublisherAdRequest.Builder adRequestBuilder)
        {
      
        // Bid was received from InMobi Audience Bidder. You may call load() on the updated ad object.
        PublisherAdRequest publisherAdRequest = adRequestBuilder.build();
      
        mPublisherInterstitialAd.loadAd(publisherAdRequest);
      
        @Override public void onBidFailed(@NonNull PublisherAdRequest.Builder adRequestBuilder, @NonNull final Error error) 
        {
      
        // No Bid received from InMobi Audience Bidder. You may call load() on the ad object.
        PublisherAdRequest publisherAdRequest = adRequestBuilder.build();
      
        mPublisherInterstitialAd.loadAd(publisherAdRequest);
      
        // Then, call update bid to kick off the bidding process interstitialBidToken.updateBid();
        });
      	

      Option B:

      If you would like to handle the keywords yourself instead, you may instead implement the IMAudienceBidderBannerKeywordListener or IMAudienceBidderInterstitialKeywordListener interface. In addition, you will have to call addCustomTargeting() on the PublisherAdRequest.Builder object.

      • For onBidReceived (meaning a bid was received from the InMobi Audience Bidder), you get returned a IMABBidResponse. You can then retrieve the following pieces of information from the IMABBidResponse:
        • getPlacement() - Returns a String that describes the InMobi placement
        • getBuyer() - Returns a String that describes the buyer
        • getPrice() - Returns a Double that describes the price
        • getBidKeyword() - Returns a String that describes a keyword that should be provided to the PublisherAdRequest.Builder object
        • getGranularKeyword() - Returns a String that describes a granular keyword

      • For onBidFailed (meaning InMobi Audience Bidder failed to give a bid), you get returned an error. You then can call loadAd() on the original DFP ad object .

      Banner Code Examples

      You will handle the keywords in this example. You will need to ensure PublisherAdRequest.Builder object is not null first. Below is an example of what you might do in your banner configuration code.

        Bundle metadata = new Bundle();
        metadata.putString(IMAudienceBidder.IMAB_PLACEMENT, placement);
        adRequestBuilder.addCustomEventExtrasBundle(IMABCustomEventBanner.class, metadata);
      	

      The key difference with this integration path is that you'll need to call setKeywords() yourself by retrieving the value from the IMABBidResponse.

        // Use a Boolean to keep track so we don't call loadAd() on the banner repeatedly.
        public Boolean bannerLoaded = false;
      
        bannerBidToken = inMobiAudienceBidder.createBidToken(this, AB_BannerPLC, dfpViewWidth, dfpviewHeight, new IMAudienceBidder.IMAudienceBidderBannerKeywordListener()
        {
        	@Override public void onBidReceived(IMAudienceBidder.IMABBidResponse imabBidResponse)
        {
      
        // Bid was received from InMobi Audience Bidder.
      
        // Parse the imaBidResponse for any additional information you need, and set them here as desired.
        adRequestBuilder.addCustomTargeting(IMAudienceBidder.IMAB_KEY, imabBidResponse.getBidKeyword());
      
        // If the banner has not yet been loaded, call loadAd to load the ad into the view
      
        if (!bannerLoaded) {
        PublisherAdRequest publisherAdRequest = adRequestBuilder.build();
      
        mPublisherAdView.loadAd(publisherAdRequest);
        }
      
        @Override public void onBidFailed(Error error)
        {
      
        // No Bid received from InMobi Audience Bidder. Call loadAd on your DFP view once you are ready.
      
        // Error handling here as desired
      
        // If the banner has not yet been loaded, call loadAd to load the ad into the view
      
        if (!bannerLoaded) {
        PublisherAdRequest publisherAdRequest = adRequestBuilder.build();
      
        mPublisherAdView.loadAd(publisherAdRequest);
        }
        }
        });
      
        // Call update bid to start this process bannerBidToken.updateBid();
      	

      For more information about DFP banner implementation specifics, you can consult the relevant DFP documentation here: https://developers.google.com/ad-manager/mobile-ads-sdk/android/banner


      Interstitial Code Examples

      You will handle the keywords in this example. You will need to ensure PublisherAdRequest.Builder object is not null first. Below is an example of what you might do in your interstitial configuration code.

        Bundle metadata = new Bundle();
        metadata.putString(IMAudienceBidder.IMAB_PLACEMENT, placement);
        adRequestBuilder.addCustomEventExtrasBundle(IMABCustomEventBanner.class, metadata);
      	

      The key difference with this integration path is that you'll need to call setKeywords() yourself by retrieving the value from the IMABBidResponse.

        interstitialBidToken = inMobiAudienceBidder.createBidToken(this, AB_InterstitialPLC, new IMAudienceBidder.IMAudienceBidderInterstitialKeywordListener()
        {
      
      @Override public void onBidReceived(IMAudienceBidder.IMABBidResponse imabBidResponse)
        {
      
        // Bid was received from InMobi Audience Bidder.
      
        // Parse the imaBidResponse for any additional information you need, and set them here as desired.
      
        adRequestBuilder.addCustomTargeting(IMAudienceBidder.IMAB_KEY, imabBidResponse.getBidKeyword());
      
        // Call load on the interstitial after all keywords have been set
        PublisherAdRequest publisherAdRequest = adRequestBuilder.build();
      
        mPublisherInterstitialAd.loadAd(publisherAdRequest);
      
        @Override public void onBidFailed(Error error) 
        {
      
      // No bid received - you may call load on the interstitial after any additional keywords have been set
      
        // Error handling here as desired
      
        PublisherAdRequest publisherAdRequest = adRequestBuilder.build();
      
        mPublisherInterstitialAd.loadAd(publisherAdRequest);
        }})
      
        // Then, call update bid to kick off the bidding process
        interstitialBidToken.updateBid();
      	

      Remember to show the interstitial! Consult DFP documentation here regarding interstitials:

      https://developers.google.com/ad-manager/mobile-ads-sdk/android/interstitial

        public void onAdLoaded() {if (interstitial.isReady()){  interstitial.show();
        }
        }
      	

      Integration Step 6: Re-use the interstitial bid token

      You can also re-use the interstitial bid token. As an example, you might include this in the onAdClosed callback from DFP.

      // Update bid for the next ad call interstitialBidToken.updateBid();
      	



      Step 1.4.1.1.3: Testing your Audience Bidding Integration

      In order to test your Audience Bidding implementation, you will need to:

      • Make sure you enable test mode on your placement through the UI
      • Set up a line item with:
        1. CPM 0.00
        2. Keyword: IMAB:0.00

      Two ways to verify:

      1. Through Charles:
        1. In the ad request we send to DFP (https://pubads.g.doubleclick.net/gampad/ads), check under “Contents” & “JSON Text”, you should see a key value pair of: “cust_params: IMAB:0.00”

      2. Through DFP Reporting:
        • In the ad request you send to DFP (ads.dfp.com/m/ad), check:
        • Under "Contents" & "JSON Text", you should see a key value pair of: "q: keywords, testing, IMAB:0.00"
        • Make sure the ad filled on testing
        • Make sure the numbers align for the newly generated line item at $0.00 (it might take a few minutes for DFP to report it).
        • Make sure the ad filled on testing.

    Step 1.4.2: Non-Audience Bidding

    Perform the following steps to initiate non-Audience bidding:

    Step 1.4.2.1: Add DFP to InMobi Adapter

    Add the following files from dist/network-support/DFP/AerServCustomEvents to your project:

    Step 1.4.2.2: Configure Ad Setup on DFP Dashboard

    Enter the following information:

    a. Class Name: Use one of the following class names:

    • For Banner: AerServDFPCustomEventBanner
    • For Interstitial: AerServDFPCustomEventInterstitial

    b. Parameter: AerServ platform ad parameters, in JSON format.

    Step 1.4.2.3: Map Plugin Events

    AerServ banner events are mapped to DFP's CustomEventBanner events, in the following manner:

    • AD_LOADED → onAdLoaded()
    • AD_FAILED → onAdFailedToLoad()
    • AD_CLICKED → onAdClicked() & onAdLeftApplication()
    • AD_DISMISSED → onAdClosed()

    AerServ interstitial events are mapped to DFP's CustomEventInterstital events, in the following manner:

    • PRELOADY_READY → onAdLoaded()
    • AD_FAILED → onAdFailedToLoad()
    • AD_DISMISSED → onAdClosed()
    • AD_IMPRESSION → onAdOpened()
    • AD_CLICKED → onAdClicked() & onAdLeftApplication()

    Version History

    SDK 9.0

    • 9.0.0: 9/20/19
      • Modular SDK

        - Added an ability to integrate Mediation as a separate module.

      • Added support for Android 10
      • Support for Mopub 5.8
      • Interface Changes
        • - APIs added
          • AerServTransactionInformation

            public String getCreativeID()

          • InMobiBanner

            public void destroy()<br>

        • - APIs removed
          • InMobiNative

            public InMobiNative(Context context, long placementId, NativeAdListener listener)

            public void setNativeAdListener(NativeAdListener listener)

          • InMobiNative.NativeAdListener
          • InMobiBanner

            public void setListener(BannerAdListener listener)

          • InMobiBanner.BannerAdListener
          • InMobiInterstitial

            public InMobiInterstitial(Context context, long placementId, InterstitialAdListener2 listener)

            public void setInterstitialAdListener(InterstitialAdListener2 listener)

          • InMobiInterstitial.InterstitialAdListener2
      • Bug fixes and performance improvements
    • 8.2.1: 8/22/19
      • Bug Fixes for SDK and AudienceBidder Plugin
    • 8.2.0: 8/5/19
      • Chrome Custom tabs support
      • Thread Optimizations
      • Bug Fixes for SDK and AudienceBidder Plugin
    • 8.1.3: 7/18/19
      • Support for Audience Bidding for DFP
      • Bug Fixes
    • 8.1.2: 6/19/19
      • Updated AdColony SDK support to 3.3.10
      • Updated Audience Network (Facebook) support to 5.3.1
    • 8.1.1: 5/27/19
      • Support for new Picasso version 2.71828
      • Bug Fixes
    • 8.1.0: 5/14/19
      • DFP Plugin Support
      • Mopub Audience Bidding Plugin Keyword Handling
    • 8.0.9: 4/22/19
      • Bug Fixes
    • 8.0.8: 4/17/19
      • Bug Fixes
    • 8.0.7: 4/5/19
      • Bug Fixes
      • Updated AudienceBidder to v1.0.1
        • Support for granular keywords
        • Fixed issue with updateBid not working with MoPub's refresh
        • Replaced source file with a aar
        • Various API Changes (see documentation)
    • 8.0.5: 3/11/19
      • Audience Bidder for the Mopub Plugin
      • Telaria Adapter Deprecation
      • Flurry Banner Adapter Deprecation
      • Applovin 3rd Party API Reporting updates
      • Chartboost 3rd Party API Reporting updates
      • Mediated SDK updates
      • Bug Fixes
    • 8.0.1: 11/28/18
      • Unified InMobi + AerServ SDK

    exchange | Audience Bidding for DFP (iOS)

    Prerequisites

    • The following environments are required:
      • iOS 9+
      • XCode 11

    Step 1: Integrating the SDK

    Step 1.1: Download the InMobi SDK

    a. Download the latest InMobi SDK below. We also provide the option to use CocoaPods! Download the InMobi iOS SDK here.

    The SDK bundle contains all media adapters that we support. Prune the downloaded folder to retain the media adapters you need.

    b. CocoaPods (Recommended)

    In the same directory as your YOUR_PROJECT.xcodeproj, create an empty file named Podfile and copy and paste the following:

    platform :ios, '9.0'
    target 'APP_NAME' do
          pod ‘InMobiABAdMobDFPPlugin’
    end
    	

    Ensure your project has been closed. Using the terminal, navigate to the directory containing the Podfile and run the command: pod install. Once the installation finishes, use YOUR_PROJECT.xcworkspace to access your project moving forward.

    Inside the xcworkspace there should be a Pods directory included with a ios-sdk-pod sub-directory.

    Warning: Please remove all older versions of the InMobi SDK (8.X.X and older) and all older versions of the AerServ SDK. Otherwise, your code will not compile! Please reach out to your account manager if you have any questions. If you are using CocoaPods, be sure to remove the 'aerserv-ios-sdk' pod from your podfile and only use the 'inmobi-ios-sdk' pod.

    • Step 1.2: Add the Required Libraries

      Add the following frameworks into your project from the InMobi SDK download:

      • InMobiSDK.framework

    Note: When using any mediation through the InMobi SDK, it is highly recommended that you use the framework that is provided along with the InMobi SDK download. These versions have been tested by our team and using any other version may not be officially supported.

    • Step 1.3: General Settings

    Under the General tab within your project's target, you'll need to add the following settings:

    • Add the following dependencies to Linked Frameworks and Libraries:
      • WebKit.framework
      • ibxml2..tbd
      • libz.tbd
      • libsqlite.3.0.tbd

    One or more of the mediation adapters that you selected requires these frameworks. For the SDKs to work properly, you MUST include these frameworks in your project.

    • Step 1.4: Create a bridging header (Swift Only)

    You will need to create a bridging header if your application is built with Swift. The bridging header exposes the Objective-C implementation to Swift. To create the bridging header, you'll need to do the following:

    1. Create a new header file, InMobiSDK-Bridging-Header.h.
    2. Add the following entry to the Bridging Header:
      #import <InMobiSDK/InMobiSDK.h>
      		
    3. Add the newly created header file's path to the target's Build Setting -> Linking -> Objective-C Bridging Header
    • Step 1.5: Build Settings

    Add the following flags to the target's Build Setting -> Linking -> Other Linker Flag:

    -ObjC

    • Step 1.6: Info.plist

    You will need to add the following entries into your info.plist:

    <key>NSLocationWhenInUseUsageDescription</key>
    <string>Location is used to help target content to your general area</string>
    <key>NSPhotoLibraryUsageDescription</key>
    <string>Some ad content may require access to the photo library.</string>
    <key>NSCameraUsageDescription</key>
    <string>Some ad content may access camera to take picture.</string>
    	

    Step 1.7.1 Audience Bidding

    To use the InMobi Audience Bidding SDK, here is how you can expect the flow to go:

    1. The InMobi Audience Bidder SDK will make an ad request and return a bid object
    2. The bid object from InMobi Audience Bidder will have an updated DFPRequest Object and have pricing keywords attached
    3. You then call loadRequest() with the DFPRequest object as before
    4. If InMobi is selected to fill, The InMobi Audience Bidder SDK will handle the rendering

    Note: Contact your account manager for Audience Bidding placement setup.

    Optionally, if you would like to handle the keywords yourself, you may also observe the below flow:

    1. The InMobi Audience Bidder SDK will make an ad request.
    2. The response from InMobi Audience Bidder will have an IMABBidResponse object
    3. You may query the object for the bid keyword, price, granular keyword, InMobi placement, and buyer.
    4. You would then append the bid keyword in customTargeting and set placement id with GADCustomEventExtras using IMABCustomEvent key to DFPRequest object.
    5. You would then call loadRequest() with the DFPRequest object as before
    6. If InMobi is selected to fill, The InMobi Audience Bidder SDK will handle the rendering

    Step 1.7.1.1 Audience Bidding Setup on DFP

    To enable Audience Bidding, you will need to do 2 things:

    1. Set up the yield group to use the specific keywords with pricing used by the IMAudienceBidder class.
    2. Update your existing DFP integration details.

    Step 1.7.1.1.1 Setting up the DFP Yield Groups
    1. Sign in to Google Ad Manager.
    2. Click Delivery > Yield groups.
    3. Click New yield group. Enter a unique yield group Name that's descriptive for reporting.
    4. Select the Ad format and Inventory type you wish to target with this yield group.
    5. Define Key values using the keyword: “IMAB” for different price points. Enter the keyword in the following format IMAB:0.00 (eg. IMAB:0.50)
    6. Then add/map the ad units to these keywords under Custom Targeting.

    7. Ad Exchange will be your default partner/demand source on the UI. Proceed to add additional third-party yield partner and select InMobi (as the ad network) to compete for the targeted inventory.

      Note: Please ensure that the CustomClass name is as follows for Banner and Interstitial

      • Banner: IMABCustomEventBanner
      • Interstitial: IMABCustomEventInterstitial

      Note: Label should be mentioned as: IMABCustomEvent.

    8. Click Save to confirm your changes without activating this yield group for delivery, or click Save and activate to confirm your changes and immediately approve this yield group for delivery.
    9. Once a yield group has been created and activated, Ad Manager is ready to begin using the yield group to fill requests.
    10. Banner Price Points

      Enter the keyword in the "Keyword targeting" in the following format IMAB:0.00 (ex. IMAB:0.50)

      eCPM

      Keyword

      eCPM

      Keyword

      <0.05

      IMAB:0.05

      1

      IMAB:1.00

      0.1

      IMAB:0.10

      1.2

      IMAB:1.20

      0.2

      IMAB:0.20

      1.4

      IMAB:1.40

      0.3

      IMAB:0.30

      1.6

      IMAB:1.60

      0.4

      IMAB:0.40

      1.8

      IMAB:1.80

      0.5

      IMAB:0.50

      2

      IMAB:2.00

      0.6

      IMAB:0.60

      2.5

      IMAB:2.50

      0.7

      IMAB:0.70

      3

      IMAB:3.00

      0.8

      IMAB:0.80

      3.5

      IMAB:3.50

      0.9

      IMAB:0.90

      >4.00

      IMAB:4.00

      Interstitial Price Points

      Enter the keyword in the "Keyword targeting" in this format IMAB:0.00 (ex. IMAB:0.50)

      eCPM

      Keyword

      eCPM

      Keyword

      <0.50

      IMAB:0.50

      7

      IMAB:7.00

      1

      IMAB:1.00

      8

      IMAB:8.00

      1.5

      IMAB:1.50

      9

      IMAB:9.00

      2

      IMAB:2.00

      10

      IMAB:10.00

      2.5

      IMAB:2.50

      12

      IMAB:12.00

      3

      IMAB:3.00

      14

      IMAB:14.00

      3.5

      IMAB:3.50

      16

      IMAB:16.00

      4

      IMAB:4.00

      18

      IMAB:18.00

      4.5

      IMAB:4.50

      20

      IMAB:20.00

      5

      IMAB:5.00

      22

      IMAB:22.00

      6

      IMAB:6.00

      >24.00

      IMAB:24.00

    Step 1.7.1.1.2 Technical Integration Details for Audience Bidding

    For Audience Bidding, here are the required changes that you'll need to do in our code:

      • Integration Step 1: Import the InMobi SDK

    The IMAudienceBidder is a part of the SDK and will be able to handle most of the functionality required for audience bidding.

    #import <InMobiSDK/InMobiSDK.h>
    	
      • Integration Step 2: Initialize InMobi Audience Bidder

    You MUST initialize the InMobi Audience Bidder before you make an ad request. Typically, the initialization step may take up to 10 seconds. The initialize method will take in your application site ID (from the InMobi platform). If you have problems finding this information, reach out to your account manager.

    Note: To set the General Data Protection Regulation (GDPR) user consent flag. Pass YES/true for user consent if GDPR user consent was granted and NO/false if user consent was denied or if unknown.

    [IMAudienceBidder initializeWithAppID:kASAppID andUserConsent:@{ IM_GDPR_CONSENT_AVAILABLE : “TRUE” }];
    	

    Notes:

        • If you would like for InMobi to handle keywords (thus simplifying your integration), follow the below steps for Option A.
        • If you would like to handle the keywords yourself instead, follow the steps for Option B. In addition, you will have to set in customTargeting and set placement id with GADCustomEventExtras using IMABCustomEvent key to DFPRequest object.
      • Integration Step 3: Create or Submit a Bid
        1. Option A: Make an ad request using the bid object

          For Option A, to easily support banner refresh and support subsequent ad requests to the InMobi Audience Bidder, we have a BidObject that you should use.The IMAudienceBidder methods will return a BidObject which you can then call our refreshBid on.

          • The +createBidForAdType: method will return a bidObject which you should retain a strong reference to:
            @property (strong, nonatomic) IMBidObject *bidObject;
            					
          • Please ensure you maintain a strong reference to the DFPRequest:
            @property (strong, nonatomic) DFPRequest *bannerRequest;
            					
          • The +createBidForAdType: method requires for you to pass in an adType, InMobi placement (PLC), DFPRequest, and delegate. Contact your InMobi account manager if you have any questions about this.
          • The adType ENUM: kIMBiddingAdTypeBanner, kIMBiddingAdTypeInterstitial.
          • The setBannerSlotSize:adSize method will use to set the banner size. By default banner size will be 320*50.
          • The +submitBid method will kick off the bidding process with the created bid object. You may review IMAudienceBidder.h for more information.

          A full example snippet for banner and interstitial is available below. InMobi will handle the keywords for you in this option:

          Banner Code Examples

          // CGSize bannerAdSize = CGSizeMake(320, 50);
          // CGSize bannerAdSize = CGSizeMake(300, 250);
          
          GADAdSize customAdSize = GADAdSizeFromCGSize(bannerAdSize);
          self.dfpRequest = [DFPRequest request];
          self.dfpBanner = [[DFPBannerView alloc] initWithAdSize:customAdSize];
          self.dfpBanner.rootViewController = self;
          self.dfpBanner.adUnitID = DFP_BANNER_ADUNIT_ID;
          self.dfpBanner.delegate = self;
          
          // Call createBidForAdType and retain a reference to the bid object to be utilized later
           self.bannerBidObject = [IMAudienceBidder createBidForAdType:kIMBiddingAdTypeBanner withPlacement:AS_BannerID_AB adObj:self.dfpRequest andDelegate:self];
          
          // Set the banner ad size [self.bannerBidObject setBannerSlotSize:bannerAdSize];
          
          // Submit the bid to kick off the bidding process [self.bannerBidObject submitBid];
          				

          Interstitial Code Examples

          self.dfpRequest = [DFPRequest request];
          self.dfpnterstitial = [[DFPInterstitial alloc] initWithAdUnitID:DFP_INT_ADUNIT_ID];
          self.dfpInter.delegate = self;
          
          // Call createBidForAdType and retain a reference to the bid object to be utilized later
          self.interstitialBidOBject = [IMAudienceBiddercreateBidForAdType:kIMBiddingAdTypeInterstitial withPlacement:AS_InterstitialID_AB adObj:self.dfpRequest andDelegate:self];
          
          // Submit the bid to kick off the bidding process [self.interstitialBidOBject submitBid];
          				
        2. Option B: Submit a bid request using submitBidForAdType

          You will not be able to use the BidObject, and you will have to repeatedly call the +submitBidForAdType: method.

          @property (strong, nonatomic) IMBidObject *bidObject;
          				
          • Please ensure you maintain a strong reference to the DFPRequest:
            @property (strong, nonatomic) IMBidObject *bidObject;
            					
          • The +submitBidForAdType: or +submitBidForAdType:adSize method requires for you to pass in an adType, InMobi placement (PLC), and delegate. Contact your InMobi account manager if you have any questions about this.
          • The adType ENUM: kIMBiddingAdTypeBanner, kIMBiddingAdTypeInterstitial
          • The +submitBidForAdType method also will kick off the bidding process (no need to call +submitBid seperately). You may review IMAudienceBidder.h for more information.

      A full example snippet for banner and interstitial is available below. You will handle the keywords in this example. Call submitBidForAdType and do not use a bid object.

      Banner code examples

      GADAdSize customAdSize = GADAdSizeFromCGSize(CGSizeMake(320, 250));
      self.dfpRequest = [DFPRequest request];
      self.dfpBanner = [[DFPBannerView alloc] initWithAdSize:customAdSize];
      self.dfpBanner.rootViewController = self;
      self.dfpBanner.adUnitID = DFP_BANNER_ADUNIT_ID;
      self.dfpBanner.delegate = self;
      
      // Call submitBidForAdType if you plan to add keywords to the object yourself [IMAudienceBidder submitBidForAdType:kIMBiddingAdTypeBanner withPlacement:AS_BannerID_AB adSize:customAdSize andDelegate:self];
      		

      Remember to add the banner to the view and call show on it once you get the bidReceived delegate callback. For more information about DFP banner implementation, you can consult the relevant DFP documentation here: https://developers.google.com/ad-manager/mobile-ads-sdk/ios/banner

      Interstitial Code Examples

      self.dfpRequest = [DFPRequest request];
      self.dfpnterstitial = [[DFPInterstitial alloc] initWithAdUnitID:DFP_INT_ADUNIT_ID];
      self.dfpInter.delegate = self;
      
      // Call submitBidForAdType if you plan to add keywords to the object yourself [IMAudienceBidder submitBidForAdType:kIMBiddingAdTypeInterstitial withPlacement:AS_InterstitialID_AB andDelegate:self];
      		

      Remember to call load on the interstitial once you get the bidReceived delegate callback. You can reference the section below as well to see an example. For more information about DFP interstitial implementation, you can consult the relevant DFP documentation here: https://developers.google.com/ad-manager/mobile-ads-sdk/ios/interstitial.

      Also, do remember to call show when the interstitial has loaded! (when you get the interstitialDidReceiveAddelegate callback from DFP)

    • Integration Step 4: Implement the IMAudienceBidderDelegate Interface
      1. Option A: The IMAudienceBidderDelegate has 2 methods that need to be implemented:
        • -audienceBidderDidReceiveBidFor:
        • -audienceBidderDidFailBidFor:

        In either scenario (banner or interstitial), you will be returned a DFPRequest for banner and interstitial. If a bid was returned from createBidForAdType, you would then be given an updated DFPRequest object. If a bid was not returned from createBidForAdType, you get returned a reference of the DFPRequest object with unmodified keywords. Below is an example delegate implementation covering both banner and interstitial:

         - (void)audienceBidderDidFailBidFor:(id)adObject withError:(NSError* ) error {
        
                // If the returned and updated adObject is a DFPRequest:
        
                if([adObject isKindOfClass:[DFPRequest class]]){
        
                    // Load the banner
        
                    [self.dfpBannerloadRequest:self.dfpRequest];
        
                    // Or load the interstitial
        
                    [self.dfpInterstitial loadRequest:self.dfpRequest];
                }
            }
            - (void)audienceBidderDidReceiveBidFor:(id)adObject {
        
                    // If the returned and updated adObject is a DFPRequest:
        
                if([adObject isKindOfClass:[DFPRequest class]]) {
        
                    // Load the banner
        
                    [self.dfpBanner loadRequest:self.dfpRequest];
        
                    // Or load the interstitial
        
                    [self.dfpInterstitial loadRequest:self.dfpRequest];
                }
            }
        			
      2. Option B: If you prefer to handle keywords yourself, the IMAudienceBidderDelegate has 2 methods that need to be implemented:
        • -audienceBidderDidGenerateBidResponse:
        • -audienceBidderDidFailBidFor:

        For these methods,You would have to append the bid keyword in customTargeting and set placement id with GADCustomEventExtras using IMABCustomEvent key to DFPRequest object. In addition, you may be returned an IMBidResponse object.

        You may access the follow properties on the object:

        • NSString* placement - A NSString that describes the InMobi placement
        • NSString* buyer - A NSString that describes the buyer
        • NSNumber* price - A NSNumber that describes the price
        • NSString* keyword - A NSString that describes a keyword that should be provided to the DFPRequestad object
        • NSString* higherGranularityKeyword - A NSString that describes a granular keyword

        In either scenario (banner or interstitial), if a bid was returned from submitBidForAdType, you would then be given a IMBidResponse object. If a bid was not returned from submitBidForAdType, you do not get returned an IMBidResponse object and you can choose to add additional keywords at this step and/or call loadAd. Below is an example delegate implementation covering both banner and interstitial:

        // Use a Boolean to keep track so you don't call loadAd on the banner repeatedly.
        Boolean bannerLoaded = false;
        
        - (void)audienceBidderDidGenerateBidResponse:(IMBidResponse *)bidResponse
        {NSArray* bidResponseKey = [bidResponse.keyword componentsSeparatedByString:@":"];
        
        NSDictionary *customTargetingDictionary;
        
        if (bidResponseKey.count == 2)
        {customTargetingDictionary = @{bidResponseKey.firstObject:bidResponseKey.lastObject};
        }
        GADCustomEventExtras *extras = [[GADCustomEventExtras alloc] init];
        
        [extras setExtras:@{kIMABLocalCacheKey : bidResponse.placement} forLabel:@"IMABCustomEvent"];
        
        [self.dfpRequest registerAdNetworkExtras:extras];
        
        // If the bid response placement is a banner
        if (bidResponse.placement == AS_BannerID_AB)
        {
        
        // Set or append the returned InMobi bidResponse keywords on the DFPRequest
        self.dfpRequest.customTargeting = customTargetingDictionary;
        
        // Set the local extras of the adview
        
        // If the banner has not yet been loaded, call loadAd on the updated DFPView
        if (!bannerLoaded){
        
        [self.dfpBanner loadRequest:self.dfpRequest]];
        }
        }
        else if (bidResponse.placement == AS_InterstitialID_AB)
        {
        
        // Set or append the returned InMobi bidResponse keywords on the interstitial
        self.dfpRequest.customTargeting = customTargetingDictionary
        
        // Set the local extras of the interstitial
        [self.dfpBanner loadRequest:self.dfpRequest];
        			
    • Integration Step 5: Implement Banner Callbacks to Support Banner Refresh with a New Bid

      We support DFP automatic banner refresh in the InMobi Audience Bidder SDK for both implementation options, A and B.

      1. Option A: You'll need to include an +submitBid method call in the DFP adViewDidReceiveAd/ didFailToReceiveAdWithErrordelegate callbacks. This will allow us to provide a fresh bid each time the banner is refreshed.

        Note: The submitBid method should only be called after the banner bid object has been constructed to avoid unexpected behavior.

        - (void)adViewDidReceiveAd:(DFPBannerView *)adView
        {
        
        // Ensure that you do not call loadAd again on the DFP Ad View
        bannerLoaded = true;
        
        // On a successful load, call submitBid for the next refresh
        [self.bannerBidObject submitBid];
        
        - (void)adView:(DFPBannerView *)adView
        didFailToReceiveAdWithError:(GADRequestError *)error
        
        // Ensure that you do not call loadAd again on the DFP Ad View
        bannerLoaded = true;
        
        // On a failed load, still call submitBid for the next banner refresh
        [self.bannerBidObject submitBid];
        			
      2. Option B: You'll need to include a new +submitBidForAdType method call in the DFP adViewDidReceiveAd / didFailToReceiveAdWithErrordelegate callbacks. This will allow us to provide a fresh bid each time the banner is refreshed.
        - (void)adViewDidReceiveAd:(DFPBannerView *)adView
        {
        
        // Ensure that we do not call loadAd again on the DFPView
        bannerLoaded = true;
        
        // On a successful load, do a new submitBidForAdType for the next refresh
        [IMAudienceBidder submitBidForAdType:kIMBiddingAdTypeBanner withPlacement:AS_BannerID_AB andDelegate:self];
        
        - (void)adView:(DFPBannerView *)adView
        didFailToReceiveAdWithError:(GADRequestError *)error
        {
        
        // Ensure that we do not call loadAd again on the DFPView
        bannerLoaded = true;
        
        // On a failed load, still call submitBidForAdType for the next banner refresh
        [IMAudienceBidder submitBidForAdType:kIMBiddingAdTypeBanner withPlacement:AS_BannerID_AB andDelegate:self];
        			
    • Integration Step 6: Get a new interstitial bid
      1. Option A: After an interstitial is shown, you can optionally call 'submitBid' on the interstitial bid object to get a new bid from the InMobi Audience Bidder.

        Note: The submitBid method should only be called after the interstitial bid object has been constructed to avoid unexpected behavior.

        [self.interstitialBidOBject submitBid];
        			
      2. Option B: After an interstitial is shown, you can optionally call 'submitBidForAdType' on to get a new bid from the InMobi Audience Bidder.
        [IMAudienceBidder submitBidForAdType:kIMBiddingAdTypeInterstitial withPlacement:AS_InterstitialID_AB andDelegate:self];
        			
    Step 1.7.1.1.3: Testing your Audience Bidding Integration

    In order to test your Audience Bidding implementation, you will need to:

        • Make sure you enable test mode on your placement through the UI
        • Set up a line item with:
        1. CPM 0.00
        2. Keyword: IMAB:0.00

    Two ways to verify:

      1. Through Charles:
        1. In the ad request we send to DFP (https://pubads.g.doubleclick.net/gampad/ads), check under “Contents” & “JSON Text”, you should see a key value pair of: “cust_params: IMAB:0.00”
      2. Through DFP Reporting:
        1. Make sure the ad filled on testing.
        2. Make sure the numbers align for the newly generated line item at $0.00 (it might take a few minutes for DFP to report it).

    Step 1.7.2 Non-Audience Bidding

    Perform the following steps to initiate non-Audience bidding:

    Step 1.7.2.1: Add DFP to InMobi Adapter

    Add the following files from dist/network-support/Google/DFP-CustomEvents/ to your project.


    Step 1.7.2.2: Configure Ad Setting on DFP Dashboard

    Enter the following information:

    • Class Name: Use one of the following class name.
      • For Banner: AerServDFPCustomEventBanner
      • For Interstitial: AerServDFPCustomEventInterstitial
    • Parameter: AerServ platform ad parameters, in JSON format.

    Step 1.7.2.3: Map Plugin Events

    InMobi banner events are mapped to DFP's CustomEventBannerDelegate events, as follows:

    • -adViewDidLoadAd: → -customEventBanner:didReceiveAd:
    • -adViewDidFailToLoadAd:withError: → -customEventBanner:didFailAd:
    • -willPresentModalViewForAd: → -customEventBannerWillPresentModal:
    • -willLeaveApplicatonFromAd: → -customEventBannerWillLeaveApplication:
    • -adWasClicked: → -customEventBannerWasClicked: & -customEventBannerWillLeaveApplication:
    • -didDismissModalViewForAd: → -customEventBannerDidDismissModal:

    InMobi interstitial events are mapped to DFP's CustomEventInterstitialDelegate events, as follows:

    • -interstitialViewControllerDidPreloadAd: → -customEventInterstitialDidReceiveAd:
    • -interstitialViewControllerAdFailedToLoad:withError: → -customEventInterstitial:didFailAd:
    • -interstitialViewControllerWillDisappear: → -customEventInterstitialWillDismiss:
    • -interstitialViewControllerDidDisappear: → -customEventInterstitialDidDismiss:
    • -interstitialViewControllerWillAppear: → -customEventInterstitialWillPresent:
    • -interstitialViewControllerAdWasTouched: → -customEventInterstitialWasClicked: & -customEventInterstitialWillLeaveApplication:

    InMobi rewarded video events are mapped to DFP's GADRewardBasedVideoAdNetworkAdapterProtocol events, as follows:

    • -interstitialViewControllerDidPreloadAd: → -adapterDidRecieveRewardBasedVideoAd:
    • -interstitialViewControllerAdFailedToLoad:withError: → -adapter:didFailToLoadRewardBasedVideoAdwithError:
    • -interstitialViewControllerDidDisappear: → -adapterDidCloseRewardBasedVideoAd:
    • -interstitialViewControllerDidAppear: → -adapterDidOpenRewardBasedVideoAd:
    • -interstitialViewControllerAdWasTouched: → -adapterDidGetAdClick: & adapterWillLeaveApplication:
    • -interstitialViewControllerDidVirtualCurrencyReward:vcData: → -adapter:didRewardUserWithReward:

    Step 2: Additional Settings

    • Step 2.1: Disabling App Transport Security for iOS 9+

      For iOS 9+, you will need to disable App Transport Security (ATS). Please refer here for more detail.

      Select your application's Info.plist, right-click on it and open as source code. Copy the following code into your Info.plist's xml.

      <key>NSAppTransportSecurity</key> <dict>
      <key>NSAllowsArbitraryLoads</key><true/> </dict>
      		
    • Step 2.2: iOS 12 Wifi Settings

      Step 2.2.1: Enable XCode WiFi Settings

      From iOS 12 onwards Apple has introduced privacy settings to access WiFi details. If the publisher decides to share wifi details, they can take advantage of targeted ads. Benefits of ad targeting are that, the ads are more useful and meaningful to users.

      How to enable Access Wifi Information

      1. Enable access WiFi information feature to your App ID.

      2. Enable access WiFi information feature for your target app from XCode capabilities.

      3. WiFi Access should get added to your App.entitlements file. If not please add the following code to your App.entitlements file.
        <dict>
             <key>com.apple.developer.networking.wifi-info</key>
             <true/>
        </dict>
        			

    • Step 2.2.2: AVAudioSession event changes in WKWebView

      WKWebView ignores AVAudioSessionCategory, Publisher can handle audio interruptions by registering to observe AVAudioSessionInterruptionnotification posted by AVAudioSession. Publisher should ensure minimum possible disruption, and the most graceful possible recovery, from the perspective of the user.

    • Step 2.2.3: Observing Audio Interruptions

      To handle audio interruptions, begin by registering to observe notifications of type AVAudioSessionInterruptionNotification.

      - (void)adViewDidReceiveAd:(DFPBannerView *)adView
      {
      
      // Ensure that we do not call loadAd again on the DFPView
      bannerLoaded = true;
      
      // On a successful load, do a new submitBidForAdType for the next refresh
      [IMAudienceBidder submitBidForAdType:kIMBiddingAdTypeBanner withPlacement:AS_BannerID_AB andDelegate:self];
      
      - (void)adView:(DFPBannerView *)adView
      didFailToReceiveAdWithError:(GADRequestError *)error
      {
      
      // Ensure that we do not call loadAd again on the DFPView
      bannerLoaded = true;
      
      // On a failed load, still call submitBidForAdType for the next banner refresh
      [IMAudienceBidder submitBidForAdType:kIMBiddingAdTypeBanner withPlacement:AS_BannerID_AB andDelegate:self];
      		

      The posted NSNotification instance contains a userInfo dictionary providing the details of the interruption. You can determine the type of interruption by retrieving the AVAudioSessionInterruptionType value from the userInfo dictionary. The interruption type indicates whether the interruption has begun or has ended. If the interruption type is AVAudioSessionInterruptionTypeEnded, the userInfo dictionary might contain an AVAudioSessionInterruptionOptions value. An options value of AVAudioSessionInterruptionOptionShouldResume is a hint that indicates whether your app should automatically resume playback if it had been playing when it was interrupted. Media playback apps should always look for this flag before beginning playback after an interruption. If it’s not present, playback should not begin again until initiated by the user. Apps that don’t present a playback interface, such as a game, can ignore this flag and reactivate and resume playback when the interruption ends.

      Please Note: There is no guarantee that a begin interruption will have a corresponding end interruption. Your app needs to be aware of a switch to a foreground running state or the user pressing a Play button. In either case, determine whether your app should reactivate its audio session.

      For more details, please refer to the following:

      1. https://developer.apple.com/documentation/avfoundation/avaudiosession/1616596-interruptionnotification
      2. https://developer.apple.com/library/archive/documentation/Audio/Conceptual/AudioSessionProgrammingGuide/HandlingAudioInterruptions/HandlingAudioInterruptions.html

    Version History

    SDK 9.0

    • 9.0.0: 9/20/19

      - Changes to support iOS 13

      - New and improved Modularised SDK design

      - Add InMobiMediationSDK.framework to your project for AerServ Mediation.

      - Addressing issue with layering of FAN banners upon refresh

      - SKStoreProductViewController crash fix.

      - Removed Support for iOS 8.

      - Removed Support for AerServ Native ad format.

      - Removed UIWebView from InMobi SDK. Viewability Partners might be using it.

      - Size reduction for both Framework and ipa inflation.

      - Various Bug Fixes and performance improvements

      - Adapter updates for the following mediation partners:

      • MoPub - v5.9.0
      • Google Mobile Ads - v7.50.0

      - APIs Added

      • IMBanner Class

        + -(void)cancel;

      • IMInterstitial Class

        + -(void)cancel;

      - APIs Added
      • ASAdView Class

        - @property (nonatomic, assign) ASEnvironmentType env;

        - @property (nonatomic, assign) ASPlatformType platform;

        - @property (nonatomic, assign) BOOL isMuted;

        - @property (nonatomic, assign) BOOL outlineAd;

        - @property (nonatomic, assign) BOOL sizeAdToFit;

        - @property (nonatomic, assign) BOOL useHeaderBidding;

        - @property (nonatomic, strong) NSArray* keyWords;

        - @property (nonatomic, assign) BOOL allowAdvertiserCloseButton;

        - -(void)forceRefreshAd;

        - -(CGSize)adContentSize;

        - -(void)rotateToOrientation:(UIInterfaceOrientation)newOrientation;

        - -(void)play;

        - -(void)pause;


      • ASAdViewDelegate Protocol

        - -(void)willLeaveApplicatonFromAd:(ASAdView*)adView;

        - -(void)adSizeChanged:(ASAdView*)adView;

        - -(void)adView:(ASAdView*)adView didFireAdvertiserEventWithMessage:(NSString*)msg;


      • ASInterstitialViewController Class

        - @property (nonatomic, assign) ASEnvironmentType env;

        - @property (nonatomic, assign) ASPlatformType platform;

        - @property (nonatomic, assign) BOOL isMuted;

        - @property (nonatomic, assign) BOOL showOutline;

        - @property (nonatomic, assign) BOOL useHeaderBidding;

        - -(void)play;

        - -(void)pause;


      • ASInterstitialViewControllerDelegate Protocol

        - -(void)interstitialViewControllerAdInteraction:(ASInterstitialViewController*)viewController;

        - -(void)interstitialViewController:(ASInterstitialViewController*)viewController didFireAdvertiserEventWithMessage:(NSString*)msg;

    • 8.2.0: 8/5/19
      • Chrome Custom tabs support
      • Thread Optimizations
      • Bug Fixes for SDK and AudienceBidder Plugin
    • 8.1.2: 7/18/19
      • Size reduction
      • Support for Audience Bidding for DFP
      • New api to set slot size for Banner in Audience Bidding
    • 8.1.1: 6/19/19
      • Updated AdColony SDK support to 3.3.10
      • Updated Audience Network (Facebook) support to 5.3.1
    • 8.1.0: 5/14/19
      • DFP Plugin Support
      • Mopub Audience Bidding Plugin Keyword Handling
      • Bug fixes
    • 8.0.8: 4/17/19
      • Bug Fixes
    • 8.0.7: 4/05/19
      • Additional support for higher granularity keywords
    • 8.0.5: 3/11/19
      • Audience Bidder for the Mopub Plugin
      • Telaria Adapter Deprecation
      • Flurry Banner Adapter Deprecation
      • Applovin 3rd Party API Reporting updates
      • Chartboost 3rd Party API Reporting updates
      • Mediated SDK updates
      • Bug Fixes
    • 8.0.2: 12/13/18
      • Mediation bug Fixes
    • 8.0.1: 11/28/18
      • Unified InMobi + AerServ SDK

    exchange | Actions Required By Publishers to Get Paid draft

    Introduction

    Publishers have to perform the following tasks to get paid by InMobi:

    1. Creating and verifying a payment profile
    2. Activating a payment profile

    Step 1: Creating and Verifying a Payment Profile

    • InMobi follows a payout cycle of 60 days. This means that your earnings for a given month will be credited to you at the end of the 60-day payout cycle.
    • You have the option of receiving your payouts via PayPal or wire transfer/RTGS.

    For payments to be made to you, you must add a payment profile to your account. Perform the following steps to specify a valid payment profile:

    Creating a PayPal Profile

    1. Log in to your InMobi account or click here.
    2. Click the drop-down list at the top right of the page, and then select Earnings.
    3. Click the Add Account button.

    4. Select your country of residence from the Select Country drop-down. See A in the screenshot above.
    5. Select PayPal under the Select Mode of Transfer drop-down. See B in the screenshot above.
    6. Enter your PayPal ID. See C in the screenshot above.
    7. Click Verify Now.
    8. You will be redirected to the PayPal login page. Enter your credentials and log in.

    9. After you login, you will be asked if you want to grant permission to InMobi to verify your PayPal payment profile. Click Grant Permission.

    10. Click Return to InMobi to go back to the InMobi Earnings page.

    Creating an Online Bank Transfer Profile

    1. Log in to your InMobi account or click here.
    2. Click the drop-down list at the top right of the page, and then select Earnings.
    3. Click the Add Account button.

    4. Select your country of residence from the Select Country drop-down. See A in the screenshot above.
    5. Select Online Bank Transfer under the Select Mode of Transfer drop-down. See B in the screenshot above.
    6. Enter bank details. See C in the screenshot above.
    7. Check Transfer my earnings to this account and click Add Account.

    Activating your Payment Profile

    To activate your profile, perform the following steps:

    1. Log in to your InMobi account, or click here.
    2. Click the drop-down list on the top right of the page, and then select Earnings.
    3. Click the option Make Active to activate your payment profile.

    Payment Terms

    Payments to publishers will be made in US dollars for all earnings for a publisher account. Payments will not be made at a property (site or app) level. The monthly earnings of a publisher against an account, provided the account qualifies to be paid, will be paid within 60 days of the end of that month. Payment frequency will be monthly.

    For example, publisher earnings in the month of January (January 1 – January 31) will be made in the month of April of the same year.

    Modes and Thresholds to Qualify

    InMobi supports the following payment modes:

    Electronic Funds Transfer to a System-Verified Bank Account

    • InMobi can pay accrued publisher earnings, subject to qualification, by Electronic Funds Transfer. To do this, the details of your bank account where payment is to be received should be verified on the InMobi portal.
    • For bank accounts in countries other than India, to qualify for payments by electronic funds transfer, the accrued unpaid earning need to exceed USD 300.
    • For electronic funds transfers to bank accounts in India, the accrued unpaid earning need to exceed USD 50 to qualify.
    • All unpaid earnings will roll over to the next payment cycle and come up for qualification again. Accrued earnings will again be compared against the minimum amount.

    PayPal Transfer to Verified PayPal Accounts

    • InMobi can pay accrued publisher earnings, subject to qualification, through PayPal. To do this, the PayPal profile where payment is to be received should verified on the InMobi portal.
    • For publishers (outside India), to qualify for payments through PayPal, the accrued unpaid earning needs to exceed USD 50. The minimum threshold to make payments through PayPal is independent of the country in which the PayPal beneficiary resides, or where the profile was created.
    • Publishers from India cannot be paid using PayPal.
    • All unpaid earnings will roll over to the next payment cycle and come up for qualification again, wherein the accrued earnings shall be compared against the minimum amount.

    exchange | Transferring Your Estimated Pending Earnings to Available Funds draft

    Overview

    If you have both advertiser and publisher accounts with InMobi, you can use the earnings from your existing publisher account to run advertising campaigns. To do this, you must transfer a part or all of your publisher earnings to your advertiser account.

    Estimated pending earnings represent the total unpaid, accrued earnings against a publisher's account at any point in time. While this is representative of the accrued earnings, it does not represent the amount the publisher will be paid in a given payment cycle.

    The actual amount paid is subject to the payment period under consideration and corrections, such as prior payments, and adjustments, if any.

    To view your estimated pending earnings,

    1. Log in to your InMobi account, or click here.
    2. Click the drop down list at the top right of the page.
    3. Select Earnings. Your Transaction History and Estimated Pending Earnings will be displayed.

    Transferring your Estimated Pending Earnings

    To transfer funds to your advertiser account, perform the following steps:

    1. Log in to your InMobi account, or click here.
    2. Click the drop down list at the top right of the page.
    3. Select Funds.

    1. Click the Add Funds button.
    2. Select the Move From Earnings option.
    3. Enter the amount you wish to transfer to your advertiser account.
      Note: The maximum amount you can enter here is the value of your current pending earnings.
    4. After the transfer request is processed, you can use these funds to run your advertising campaigns with InMobi.

    exchange | Viewing earnings history draft

    This page shows you all earnings-related transactions made on your account. To view your transaction history, perform these steps:

    1. Log in to your InMobi account, or click here.
    2. Click the drop-down list at the top right of the page, and then click Earnings.
    3. The transaction details are available as shown below:

    Note:
    You can view your transaction history for different periods by selecting different time ranges, either preset or custom.
    You can export your transaction history to a CSV or Excel file by clicking the Export option, circled in red above.

    exchange | iOS Mopub new draft

    Getting Started with iOS Integration

    Integrating and monetizing InMobi SDK with Mopub is easy. Please refer this guide for integration instructions.

    You have access to the following ad types from InMobi via Mopub mediation:

    • Banner
    • Medium - Banner
    • Fullscreen (Interstitial, Full-screen Video Ads)
    • Rewarded Video
    • Native

    Before you begin setting up InMobi as an ad source on Mopub dashboard, it’s important that you create an InMobi account, register your app, configure placements and complete the payment information. You can learn more about it here.

    If you have completed the above steps, they you are all good to begin setting up InMobi as an adsource on Mopub. Let’s begin!

    Step 1: Configuring InMobi as an Ad Source on MoPub’s Dashboard

    Log on to your MoPub account and identify the ad units that you wish to monetize via InMobi. Then, navigate to the Networks tab.

    1. To monetize via InMobi, select Custom SDK Network. It allows you to integrate InMobi via MoPub with plug-n-play “Custom Events”.

      Note: You need both the InMobi SDK and the custom event for successful integration.

    2. Navigate to the specific ad unit that you want to monetize via InMobi.

    3. Enter the name of InMobi custom event class specific for that particular ad format as Custom Event Class value. For example, Interstitial Ad - the custom event is called: “com.inmobi.showcase.InMobiInterstitialCustomEvent”.

      Use fully qualified Custom Event class names. Here is the complete grid for custom events by ad unit type:

      Ad Unit

      Class Name

      Banner

      <your_package_name>.InMobiBannerCustomEvent

      Medium (300x250 banner)

      <your_package_name>.InMobiBannerCustomEvent

      Fullscreen

      <your_package_name>.InMobiInterstitialCustomEvent

      Rewarded Video

      <your_package_name>.InMobiRewardedCustomEvent

      Native

      <your_package_name>.InMobiNativeCustomEvent/

      <your_package_name>.InMobiNativeStrandCustomEvent

      Note: Please note that the package name <your_package_name> should be replaced with the actual package name in which the custom event classes are placed in the app.

    4. Your account ID is available in your InMobi account as illustrated in the screenshot below.

    5. Placement ID is present under the placements section as illustrated in the screenshot below.

    6. Enter the Account ID and the Placement ID in the following format in the placeholder for Custom Event Class Data.

      {“placementid”: “<Enter your InMobi Placement ID here>”,”accountid”:”<Enter your InMobi Account ID here>”}

      A sample input will look like this:
      {“placementid”:”1468850508657”,”accountid”:”2072131215e04a5ea20e25ffec1a7171”}

    Step 2: Adding the InMobi SDK and CustomEvent to Your Project

    Integrating the InMobi SDK and the custom event to your project is fairly seamless. But before we begin, let’s pause for some checks:

    Important Prerequisites:

    Checkpoint 1: Preparing your App for iOS 10

    App Transport Security (ATS), a default setting introduced with iOS 9 that mandates apps to make network connections only over TLS version 1.2 and later. Though InMobi is committed towards the adoption of HTTPS, the current setup requires our demand partners to support this change and be 100% compliant with all the requirements of ATS.

    While we work with our partners progressing towards a secure environment, to ensure ads work on iOS 9 and later versions, you need to follow these steps as a near-term fix:

    • Disable ATS (Recommended) - to ensure non-secure content from the partners work correctly in your updated apps. To disable ATS flag, add the following code snippet to your app's Info.plist.

      <key>NSAppTransportSecurity</key>
      <dict>
        <key>NSAllowsArbitraryLoads</key>
        <true/>
      </dict>
            
    • Disable ATS with exceptions (Not Recommended) - in case you plan to migrate towards ATS compliance. You can achieve so by allowing secure content from your domains by adding them on the exception list.
      <key>NSAppTransportSecurity</key>
            <dict>
               <key>NSAllowsArbitraryLoads</key>
             <true/>
                <key>NSExceptionDomains</key>
                 <dict>
                       <key>example.com</key>
                     <dict>
                           <key>NSIncludesSubdomains</key>
                           <true/>
                       </dict>
                  </dict>
      </dict>
            

    Remember: Refrain from using InMobi domains and CDN in the exception list as it will result in errors during the runtime.

    App Store Review

    If ATS is not disabled for apps, monetization will be impacted on devices running iOS 9+. The demand ecosystem has yet to migrate to SSL enabled world, causing ads not to render. The ATS disablement will trigger additional App Store review for your app, and requires you to provide justification. A sample of justification for consideration:

    For monetization must support serving ads from the advertisers that do not support secure connections.

    Checkpoint 2: iOS 12 WiFi Settings

    Apple has introduced privacy settings to access WiFi details from iOS 12 onwards. To boost monetization and relevant user experience we encourage sharing WiFi details for targeted advertising.

    1. Enable ‘Access WiFi Information’ on your App ID.

    2. Enable access ‘Access WiFi Information’ for your target app from XCode capabilities.

    3. Ensure WiFi Access is added to your App.entitlements file.

    Step 3: Adding the InMobi SDK to Your Project

    Option 1: Integration via Cocoapods

    1. If you are not already using Cocoapods, go to your Xcode project directory and create a pod file using the command below.
        pod init
            
    2. Add the following to Podfile.
        pod 'InMobiSDK'
            
    3. Once you have added it to the pod file, run the command below to complete the task for dependency. You now have a workspace with the pods.
        pod install
            

    Option 2: Integrating the framework directly

    Alternatively, you can integrate the framework directly.

    1. Add the following MANDATORY frameworks to your Xcode project:
      • InMobiSDK.framework from the downloaded InMobi iOS SDK bundle
      • libsqlite3.0.tbd
      • libz.tbd
      • WebKit.framework

    2. Add -ObjC flag to the Other Linker Flags:
      • Open your project in Xcode.
      • Select Application Target > Build Settings.
      • In the Search box, search for Other Linker Flags.
      • Add the -ObjC flag

      Note: Do not remove window property from the AppDelegate.h file as it may lead to an undefined behavior.

    Step 3.1: Add the Custom Event

    Add the custom events to your MoPub project. The custom events for different ad formats are available as part of the sample code available here .

    Code Steps

    The code steps remain the same as they are for regular MoPub integration for fetching and loading an ad. Use the regular MoPub “ad unit id” to request and fetch an ad.

    Step 3.2 Passing user consent information to InMobi SDK

    The publishers monetizing in EEA+UK+Switzerland region will have to pass user consent to InMobi SDK. The publishers can use consent gathering mechanism of their choice, and they will have to pass on this consent information to InMobi.

    • Copy the InMobiGDPR class file from InMobiAdapter folder, into your project.

    • Use [InmobiGDPR grantConsent] or [InmobiGDPR revokeConsent] APIs to pass on user consent. Publisher will have to grant or revoke consent based on the consent provided by the user. It should be called once every session. In case grantConsent() is not called, we will presume that consent is not available for users belonging to EEA+UK+Switzerland region.
    • If the user consent is revoked at any point of time, the publisher has to call [InmobiGDPR revokeConsent] to notify InMobi about the same.
    • Use [InMobiGDPR isGDPRApplicable: (bool) flag ] to let InMobi know whether user belongs to GDPR compliant region.

    More Information

    You can see the complete sample code and example here

    The latest documentation and code samples for the MoPub SDK are available here.

    Step 4: Testing the Integration

    To ensure Mopub SDK relays the ad request to InMobi for testing, you can do the following.

    1. Set manual Ad network optimization for every network including MoPub.
    2. Set manual eCPM floors for all networks keeping the eCPM floor for InMobi higher than other networks, this will ensure that the ad request gets relayed to InMobi for testing. For example for InMobi set the floor to $5 while MoPub marketplace is set to $0.05.


    Step 4.1: Enabling Key SDK Logs

    Enable debug logs by adding following to didFinishLaunchingWithOptions method within the app delegate's .m file, as shown below:

    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
    {    
    [IMSdk setLogLevel:kIMSDKLogLevelDebug]; 
    //Initialize InMobi SDK with your account ID
    [IMSdk initWithAccountID:@"Insert InMobi account ID here"];
    //Set log level to Debug
      // Do your stuff.
      return YES;
    }
        

    You can also use the feedback available on the diagnostics tab in the InMobi dashboard (for ad unit and ad request).

    ">

    Step 5: Advanced Configurations

    Pass the location information to allow better ad targeting.

    Recommended: If your app collects location from the user, we recommend passing it up, as impressions with location signal have higher revenue potential. InMobi SDK will automatically pass the location signals if available in the app. If you use location in your app, but would like to disable passing location signals to InMobi, then TURN OFF the “Location Automation” for your property on the InMobi dashboard.

    Otherwise, modify the Custom Event class for your ad-unit to pass on the data using the InMobi SDK API. Please see sample code for more details.

    InMobi supports the following parameters:

    Method Name

    Value

    Description

    setAgeGroup:

    kIMSDKAgeGroupBelow18,

    kIMSDKAgeGroupBetween18And24

    kIMSDKAgeGroupBetween25And29

    kIMSDKAgeGroupBetween30And34

    kIMSDKAgeGroupBetween35And44

    kIMSDKAgeGroupBetween45And54

    kIMSDKAgeGroupBetween55And65

    kIMSDKAgeGroupAbove65

    The age group of the user

    setLocation:

    CLLocation object

    Setting up demographic parameters

    Here is a sample for setting up the InMobi SDK Demographic params. Publishers are requested to set the values of params as they want:

    [IMSDK setAgeGroup:kIMSDKAgeGroupBetween18And24];
    [IMSdk setGender:kIMSDKGenderMale];
        

    Audio Handling in WKWebView

    For publishers running any audio or video media as the main content, we recommend listening to interruptions by observing AVAudioSessionInterruptionnotification posted by AVAudioSession. This will help preempt any content interruptions and help address user experience issues upfront. For more information read these Apple documents: Article 1, Article 2

    Note: In case you want to write your own custom event class to integrate InMobi via MoPub please see here

    exchange | Android Admob new draft

    Getting Started with Android Integration

    Integrating and monetizing InMobi SDK with AdMob is easy. Please refer this guide for integration instructions.

    You have access to the following ad types from InMobi via AdMob mediation:

    • Banner
    • Interstitial (Static Interstitial and Full-screen Video Ads)
    • Rewarded Interstitial
    • Native

    Before you begin setting up InMobi as an ad source on AdMob dashboard, it’s important that you create an InMobi account, register your app, configure placements and complete the payment information. You can learn more about it here.

    If you have completed the above steps, then you are all good to begin setting up InMobi as an adsource on AdMob. Let’s begin!

    Step 1: Configuring InMobi as an Ad Source on AdMob Dashboard

    Logon to your AdMob account and navigate to the specific ad-unit that you want to monetize via the InMobi SDK. Under mediation, navigate to “ad-sources” (if you have integrated solely with AdMob, number of ad sources will be one).

    1. Select new ad network and add InMobi as ad source

    2. In the Network Settings page for InMobi, insert your InMobi account ID and placement ID.

      Your account ID is available in your InMobi account as illustrated in the screenshot below.

      Your Placement ID is present under the placement section in the InMobi dashboard, as illustrated in the screenshot below.

    3. Setting up Ad network optimization: For automatic eCPM optimization, the publisher must provide his/her InMobi reporting API credentials in the AdMob UI. If you want to find your API credentials, go to Account settings->API Key-> Generate Key. Reach out to InMobi support in case you face any issues.


    Step 1.1. Setting up Rewarded Interstitials
    • You can configure the reward either on AdMob’s dashboard or on InMobi’s dashboard.

    • To configure the same on InMobi’s dashboard, choose “Use third-party ad network settings”.

    • Fill in the key-value pair for the reward details, which the InMobi SDK will honour once the user completes watching the video. AdMob will in turn pass this back in the reward callback. For example, you could fill in the following reward details:

    Key = Coins, Value = 1000

    Note: While setting up the rewards on InMobi dashboard, please make sure the reward value is in the form of Integer.


    Step 1.2. Setting up Native Ads

    When creating a native content placement type on the InMobi dashboard to support a native ad unit on AdMob’s dashboard, ensure you don’t change the key names on InMobi dashboard. This is to ensure that the InMobi integration works seamlessly on native ad formats.

    Remember:

    • InMobi Adapter doesn’t honor shouldRequestMultipleImages flag for Native Ads in AdMob SDK.
    • InMobi Adapter also doesn’t honor getImageOrientation/preferredImageOrientation flag in AdMob SDK.

    Step 2: Adding the SDK to your Project

    Option 1: Pulling the Latest SDK via JCenter

    If you are using Gradle to build your Android applications, you can pull the latest version of the SDK from JCenter as described below:

    1. Include JCenter in your top-level build.gradle file
      allprojects {
          repositories {
              jcenter()
          }
      }
            
    2. Add the following line to the dependencies element in your application module’s build.gradle.
      implementation 'com.inmobi.monetization:inmobi-ads:9.0.0'
            
    3. Sync your Gradle project to ensure that the dependency is downloaded by the build system.
    Option 2: Adding the SDK Library to your Application Project

    Alternately, you can download the latest version of InMobi’s SDK here and copy the library to your application module’s libs/ directory.

    To add the library to your project’s dependencies, add this line to the dependencies element in your module’s build.gradle:

                implementation fileTree(dir: 'libs', include: ['*.aar])
        

    Step 2: Adding and Verifying the Dependencies

    To monetize with the InMobi Ad SDK, you must add the following dependencies to your application module build.gradle:

    Google Play Services

    The InMobi SDK for Android needs the Google Play Services library to enable better ad targeting via the Google Play Advertising ID. Additionally, the SDK also uses the Google Play Services for getting a location fix, should the user consent to collecting their location.

    To add the Google Play Services client library to your application:

    1. Add the following lines to the application module’s dependency element:
      implementation 'com.google.android.gms:play-services-ads-identifier:17.0.0'
      implementation 'com.google.android.gms:play-services-location:17.0.0'
            
    2. Sync your Gradle project to ensure that the dependencies are included.
    Chrome Custom Tab

    This is required to redirect the users to URLs outside InMobi WebView. To add the Chrome Custom library to your application:

    1. Add the following line to the application module's dependency element in the Gradle build script:
          implementation 'com.android.support:customtabs:28.0.0'
            
    2. Sync your Gradle project to ensure dependencies are included.
    Picasso Library

    The InMobi SDK for Android uses the popular Picasso library for loading the ad assets. To add the Picasso library to your application:

    1. Add the following line to the application module’s dependency element in the gradle build script.
                  implementation 'com.squareup.picasso:picasso:2.71828'
            
    2. Sync your Gradle project to ensure that the dependencies are included.

    Note: Failure to include Picasso dependency in your application gradle scripts will cause interstitial ad requests to fail, thus affecting monetization of your app with the InMobi SDK.

    Support Library

    For supporting paged scroll of a deck of images or ads, you must use support-v4 library.

    To do so, add the following line to the application module’s dependency element in the Gradle build script.

                implementation '<strong>com.android.support:support-v4:28.0.0</strong>'
        
    RecyclerView

    For supporting free scroll of a deck of images or ads, you must use RecyclerView.

    To do so, add the following line to the application module’s dependency element in the Gradle build script.

                implementation '<strong>com.android.support:recyclerview-v7:27.1.0</strong>'
        

    Note: Failure to include RecyclerView dependency in your application gradle scripts will cause interstitial ad requests to fail, thus affecting monetization of your app with the InMobi SDK.

    Miscellaneous

    At times, including the InMobi SDK may cause the 64K limit on methods that can be packaged in an Android dex file to be breached. This can happen if, for example, your app packs a lot of features for your users and includes substantive code to realize this.

    If this happens, you can use the multidex support library to enable building your app correctly. To do this:

    1. Modify the defaultConfig mark your application as multidex enabled:
          defaultConfig {
                  applicationId "com.inmobi.samples"
                  minSdkVersion 15
                  targetSdkVersion 29 
                  versionCode 1
                  versionName "1.0.0"
                  multiDexEnabled true // add this to enable multi-dex
              }
            
    2. Add the following line to the dependencies element in your application module’s build script.
                  implementation 'com.android.support:multidex:1.0.3'
            

    Step 2.1: Additional Configurations

    Granting Permissions

    It is highly recommended that you include ACCESS_FINE_LOCATION to enable better ad targeting. This is not a mandatory permission; however, including it will enable accurate ad targeting.

                <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
        

    For further improved targeting, you can add the ACCESS_WIFI_STATE and CHANGE_WIFI_STATE permissions to the manifest.

              <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
              <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
        
    Hardware Acceleration

    Hardware acceleration allows you to display HTML5 video ads. To do this, add hardwareAccelerated:true element to the application tag.

    <application
        ...
        android:hardwareAccelerated="true"
        ...
    >
        
    Proguard Configuration

    Proguarding helps to remove unused symbols and reduce the final application footprint. The following proguard directives should be added to your application’s proguard configuration file:

    -keepattributes SourceFile,LineNumberTable
    -keep class com.inmobi.** { *; }
    -keep public class com.google.android.gms.**
    -dontwarn com.google.android.gms.**
    -dontwarn com.squareup.picasso.**
    -keep class com.google.android.gms.ads.identifier.AdvertisingIdClient{
         public *;
    }
    -keep class com.google.android.gms.ads.identifier.AdvertisingIdClient$Info{
         public *;
    }
    # skip the Picasso library classes
    -keep class com.squareup.picasso.** {*;}
    -dontwarn com.squareup.okhttp.**
    # skip Moat classes
    -keep class com.moat.** {*;}
    -dontwarn com.moat.**
    # skip AVID classes
    -keep class com.integralads.avid.library.* {*;}
        

    Important Prerequisites:

    Let’s pause for some checks before we begin initializing the SDK:

    Checkpoint 1: Preparing Your App for Android 10

    InMobi SDK is compatible with Android 10 (API level 29), the latest version of the Android platform.

    On Android P onwards, apps make connections over HTTPS by default. Though InMobi supports the adoption of HTTPS, the current setup requires our demand partners to support HTTPS as well. The publisher can change their settings to HTTP if it has an impact on the revenue potential.

    Checkpoint 2: Preparing Your App for AndroidX

    InMobi SDK is compatible with AndroidX (JetPack) library. In case your app uses the AndroidX library, then follow the standard guidelines by Google for migration by adding both the flags in build file.

              android.useAndroidX=true
              android.enableJetifier=true
        

    It is highly recommended to upgrade Android Gradle plugin version to 4.1 or greater to avoid known issues in the jetifier which is fixed in the latest Gradle plugin version. To upgrade Android gradle plugin version please refer to Android developer documentation.

    Step 2.3: Adding the InMobi Adapter to Your Project

    Download the adapter from here. Add the InMobi adapter to your Android Studio project.

    Code Steps

    The code steps remain the same as they are for regular AdMob integration for fetching and loading an ad. Use the AdMob account ID to initialize the AdMob SDK and AdMob “ad unit id” to request and fetch an ad.

    Step 2.4 Passing user consent information to InMobi SDK

    The publishers monetizing in EEA region will have to pass user consent to InMobi SDK. The publishers can use consent gathering mechanism of their choice (like Consent SDK ), and they will have to pass on this consent information to InMobi. To pass consent information, the publisher has to call: InMobiConsent.updateGDPRConsent( consentObj )

    The consentObj will be a JSON object with the following keys:

    Key

    Type

    Inference

    gdpr_consent_available

    boolean

    "true" raspberryublisher has provided consent to collect and use user’s data.

    "false" : Publisher has not provided consent to collect and use user’s data.

    Any value other than “true” and “false” is invalid and will be treated as value not provided by publisher, i.e. empty value.

    gdpr

    Number

    Whether or not the request is subjected to GDPR regulations, deviation from the set values (0 = No, 1 = Yes ), indicate an unknown entity.

    More Information

    Please download the sample code from here.

    The latest documentation and code samples for the AdMob SDK are available here.

    Step 3: Testing the Integration

    To ensure AdMob SDK relays the ad request to InMobi for testing, you can do the following.

    1. Set manual Ad network optimization for every network including AdMob. Uncheck the “Ad network optimization” checkbox.
    2. Set manual eCPM floors for all networks keeping the eCPM floor for InMobi higher than other networks, this will ensure that the ad request gets relayed to InMobi for testing. In the example below, InMobi floor is set to $5 and AdMob is set to $0.01.

    After performing the steps mentioned above, you can test and relay the requests to InMobi SDK for ad loads.


    Step 3.1 Enabling Key SDK Logs

    You can enable key SDK logs by adding the following line to your Activity where you are integrating the ad-units.

    InMobiSdk.setLogLevel(LogLevel.DEBUG);
        

    You can also leverage feedback available on the diagnostics tab on the ad unit and ad request if you have enabled “Test Mode” on InMobi portal.

    <

    Step 4: Advanced Configurations

    Providing Location and Demographics Data

    Recommended: If your app collects location from the user, we recommend passing it up, as impressions with location signal have higher revenue potential. InMobi SDK will automatically pass the location signals if available in the app. If you use location in your app, but would like to disable passing location signals to InMobi, then TURN OFF the “Location Automation” for your property on the InMobi dashboard.

    Otherwise: You can pass the location signals in the mediation ad request object by calling the setLocation() API of MediationAdRequest class of the Admob SDK.

    InMobi supports passing the following user demographic parameters:

    Key Name

    Value

    Description

    InMobiNetworkKeys.AGE_GROUP

    InMobiNetworkValues.ABOVE_55,

    InMobiNetworkValues.BELOW_18,

    InMobiNetworkValues.BETWEEN_18_AND_20,

    InMobiNetworkValues.BETWEEN_25_AND_34,

    InMobiNetworkValues.BETWEEN_35_AND_54,

    InMobiNetworkValues.BETWEEN_21_AND_24

    The age group of the user

    InMobiNetworkKeys.EDUCATION

    InMobiNetworkValues.EDUCATION_HIGHSCHOOLORLESS,

    InMobiNetworkValues.EDUCATION_COLLEGEORGRADUATE,

    InMobiNetworkValues.EDUCATION_POSTGRADUATEORABOVE

    The education level

    • High school, or less
    • College, or graduate
    • Postgraduate, or above

    InMobiNetworkKeys.AGE

    Any String

    The age of the user

    InMobiNetworkKeys.INTERESTS

    Any String

    Any additional relevant description of the user, or their preferences, separated by commas. Valid acceptable values are mentioned below

    InMobiNetworkKeys.POSTAL_CODE

    Any String

    The postal code (usually a 5 digit number)

    InMobiNetworkKeys.AREA_CODE

    Any String

    The area code (part of the telephone number)

    InMobiNetworkKeys.LANGUAGE

    Any String

    The native language of the user (if known)

    InMobiNetworkKeys.CITY

    Any String

    City

    InMobiNetworkKeys.STATE

    Any String

    State

    InMobiNetworkKeys.COUNTRY

    Any String

    Country

    InMobiNetworkKeys.LOGLEVEL

    InMobiNetworkValues.LOGLEVEL_NONE,

    InMobiNetworkValues.LOGLEVEL_DEBUG,

    InMobiNetworkValues.LOGLEVEL_ERROR

    Log level for InMobi SDK

    exchange | iOS Admob new draft

    Getting Started with iOS Integration

    Integrating and monetizing InMobi SDK with AdMob is easy. Please refer this guide for integration instructions.

    You have access to the following ad types from InMobi via AdMob mediation:

    • Banner
    • Interstitial (Static Interstitial and Full-screen Video Ads)
    • Rewarded Interstitial
    • Native

    Before you begin setting up InMobi as an ad source on AdMob dashboard, it’s important that you create an InMobi account, register your app, configure placements and complete the payment information. You can learn more about it here.

    If you have completed the above steps, then you are all good to begin setting up InMobi as an adsource on AdMob. Let’s begin!

    Step 1: Configuring InMobi as an Ad Source on AdMob Dashboard

    Logon to your AdMob account and navigate to the specific ad-unit that you want to monetize via the InMobi SDK. Under mediation, navigate to “ad-sources” (if you have integrated solely with AdMob, number of ad sources will be one).

    1. Select new ad network and add InMobi as ad source

    2. In the Network Settings page for InMobi, insert your InMobi account ID and placement ID.

      Your account ID is available in your InMobi account as illustrated in the screenshot below.

      Your Placement ID is present under the placement section in the InMobi dashboard, as illustrated in the screenshot below.

    3. Setting up Ad network optimization: For automatic eCPM optimization, the publisher must provide his/her InMobi reporting API credentials in the AdMob UI. If you want to find your API credentials, go to Account settings->API Key-> Generate Key. Reach out to InMobi support in case you face any issues.


    Step 1.1. Setting up Rewarded Interstitials
    • You can configure the reward either on AdMob’s dashboard or on InMobi’s dashboard.

    • To configure the same on InMobi’s dashboard, choose “Use third-party ad network settings”.

    • Fill in the key-value pair for the reward details, which the InMobi SDK will honour once the user completes watching the video. AdMob will in turn pass this back in the reward callback. For example, you could fill in the following reward details:

    Key = Coins, Value = 1000

    Note: While setting up the rewards on InMobi dashboard, please make sure the reward value is in the form of Integer.


    Step 1.2. Setting up Native Ads

    When creating a native content placement type on the InMobi dashboard to support a native ad unit on AdMob’s dashboard, ensure you don’t change the key names on InMobi dashboard. This is to ensure that the InMobi integration works seamlessly on native ad formats.

    Remember:

    • InMobi Adapter doesn’t honor shouldRequestMultipleImages flag for Native Ads in AdMob SDK.
    • InMobi Adapter also doesn’t honor getImageOrientation/preferredImageOrientation flag in AdMob SDK.

    Step 2: Integrating InMobi SDK via AdMob Adapter

    Integrating the InMobi SDK and the AdMob Adapter is fairly seamless. To get an ad from InMobi, you need to incorporate both InMobi SDK and the Adapter. But before we begin, let’s pause for some checks:

    Important Prerequisites:

    Checkpoint 1: Preparing your App for iOS 10

    App Transport Security (ATS), a default setting introduced with iOS 9 that mandates apps to make network connections only over TLS version 1.2 and later. Though InMobi is committed towards the adoption of HTTPS, the current setup requires our demand partners to support this change and be 100% compliant with all the requirements of ATS.

    While we work with our partners progressing towards a secure environment, to ensure ads work on iOS 9 and later versions, you need to follow these steps as a near-term fix:

    • Disable ATS (Recommended) - to ensure non-secure content from the partners work correctly in your updated apps. To disable ATS flag, add the following code snippet to your app's Info.plist.

        <key>NSAppTransportSecurity</key><br>
        <dict><br>
        <key>NSAllowsArbitraryLoads</key><br>
        <true/><br>
        </dict>
            
    • Disable ATS with exceptions (Not Recommended) - in case you plan to migrate towards ATS compliance. You can achieve so by allowing secure content from your domains by adding them on the exception list.
      <key>NSAppTransportSecurity</key>
            <dict>
               <key>NSAllowsArbitraryLoads</key>
             <true/>
                <key>NSExceptionDomains</key>
                 <dict>
                       <key>example.com</key>
                     <dict>
                           <key>NSIncludesSubdomains</key>
                           <true/>
                       </dict>
                  </dict>
      </dict>
            

    Remember: Refrain from using InMobi domains and CDN in the exception list as it will result in errors during the runtime.

    Checkpoint 2: iOS 12 WiFi Settings

    Apple has introduced privacy settings to access WiFi details from iOS 12 onwards. To boost monetization and relevant user experience we encourage sharing WiFi details for targeted advertising.

    1. Enable ‘Access WiFi Information’ on your App ID.

    2. Enable access ‘Access WiFi Information’ for your target app from XCode capabilities.

    3. Ensure WiFi Access is added to your App.entitlements file.

    Step 3: Adding the InMobi SDK to Your Project

    Option 1: Integration via Cocoapods

    1. If you are not already using Cocoapods, go to your Xcode project directory and create a pod file using the command below.
      pod init
            
    2. Add the following to Podfile.
      pod 'InMobiSDK'
            
    3. Once you have added it to the pod file, run the command below to complete the task for dependency. You now have a workspace with the pods.
      pod install
            

    Option 2: Integrating the framework directly

    Alternatively, you can integrate the framework directly.

    1. Add the following MANDATORY frameworks to your Xcode project:
      • InMobiSDK.framework from the downloaded InMobi iOS SDK bundle
      • libsqlite3.0.tbd
      • libz.tbd
      • WebKit.framework

    2. Add -ObjC flag to the Other Linker Flags:
      • Open your project in Xcode.
      • Select Application Target > Build Settings.
      • In the Search box, search for Other Linker Flags.
      • Add the -ObjC flag

    Step 3.1: Adding the InMobi Adapter to Your Project

    Download the adapter from here. Add the InMobi adapter bundle to your Xcode project.

    Code Steps

    The code steps remain the same as they are for regular AdMob integration for fetching and loading an ad. Use the AdMob account ID to initialize the AdMob SDK and AdMob “ad unit id” to request and fetch an ad.

    Note: Do not remove window property from the AppDelegate.h file as it may lead to an undefined behavior.

    Step 3.2 Passing user consent information to InMobi SDK

    The publishers monetizing in EEA region will have to pass user consent to InMobi SDK. The publishers can use consent gathering mechanism of their choice (like Consent SDK ), and they will have to pass on this consent information to InMobi. To pass consent information, the publisher has to call: [GADMInMobiConsent updateGDPRConsent:consentObj];

    The consentObj will be a JSON object with the following keys

    Key

    Type

    Inference

    gdpr_consent_available

    boolean

    "true" - Publisher has provided consent to collect and use user’s data.

    "false" - Publisher has not provided consent to collect and use user’s data.

    Any value other than “true” and “false” is invalid and will be treated as value not provided by publisher, i.e. empty value.

    gdpr

    String

    Whether or not the request is subjected to GDPR regulations, deviation from the set values (0 = No, 1 = Yes ), indicate an unknown entity.

    More Information

    Please download the sample code from here.

    The latest documentation and code samples for the AdMob SDK are available here.

    Step 4: Testing the Integration

    To ensure AdMob SDK relays the ad request to InMobi for testing, you can do the following.

    1. Set manual Ad network optimization for every network including AdMob. Uncheck the “Ad network optimization” checkbox.
    2. Set manual eCPM floors for all networks keeping the eCPM floor for InMobi higher than other networks, this will ensure that the ad request gets relayed to InMobi for testing. In the example below, InMobi floor is set to $5 and AdMob is set to $0.01.

    Once you have completed the above steps, you can test and relay the requests to InMobi SDK for ad loads.


    Step 4.1 Enabling Key SDK Logs

    Enable debug logs by adding following to didFinishLaunchingWithOptions method within the app delegate's .m file, as shown below:

    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
    {    
      //Initialize InMobi SDK with your account ID
    [IMSdk initWithAccountID:@"Insert InMobi account ID here"];
    //Set log level to Debug
    [IMSdk setLogLevel:kIMSDKLogLevelDebug]; 
      // Do your stuff.
      return YES;
    }
        

    You can also use the feedback available on the diagnostics tab in the InMobi dashboard (for ad unit and ad request).

    Step 5: Advanced Configurations

    Providing Location and Demographics Data

    Recommended: If your app collects location from the user, we recommend passing it up, as impressions with location signal have higher revenue potential. InMobi SDK will automatically pass the location signals if available in the app. If you use location in your app, but would like to disable passing location signals to InMobi, then TURN OFF the “Location Automation” for your property on the InMobi dashboard.

    Otherwise: Location can be passed using following method under GADInMobiExtras.h.

      - (void)setLocation:(CLLocation*)location;
        

    All non-context specific parameters can be passed to InMobi for richer ad targeting. Please ensure that you pass on the values for the fields which you collect, and have user consent to share this data. Class "GADInMobiExtras" provides methods to set demographic information about the user.

    InMobi supports the following parameters:

    Method Name

    Value

    Description

    setAgeGroup

    kIMSDKAgeGroupBelow18

    kIMSDKAgeGroupBetween18And24

    kIMSDKAgeGroupBetween25And29

    kIMSDKAgeGroupBetween30And34

    kIMSDKAgeGroupBetween35And44

    kIMSDKAgeGroupBetween45And54

    kIMSDKAgeGroupBetween55And65

    kIMSDKAgeGroupAbove65

    The age group of the user

    setEducationType

    kIMSDKEducationHighSchoolOrLess kIMSDKEducationCollegeOrGraduate kIMSDKEducationPostGraduateOrAbove



    The education level

    • High school, or less
    • College, or graduate
    • Postgraduate, or above

    setAge

    Integer

    The age of the user

    setInterests

    Any String

    Any additional relevant description of the user, or their preferences, separated by commas. Valid acceptable values are mentioned below

    setPostalCode

    Any String

    The postal code (usually a 5 digit number)

    setAreaCode

    Any String

    The area code (part of the telephone number)

    setLanguage

    Any String

    The native language of the user (if known)

    setLocationWithCityStateCountry

    Any String

    Sets location with City, State, Country being passed

    setKeywords

    Any String

    Keywords to be passed in the ad request

    Setting up demographic params

    Here is a sample for setting up the InMobi SDK Demographic params. Publishers are requested to set the values of params as they want:

    InMobiSdk.setAreaCode("080");
    InMobiSdk.setEducation(Education.HIGH_SCHOOL_OR_LESS);
    InMobiSdk.setGender(Gender.MALE);
    InMobiSdk.setAge(23);
    InMobiSdk.setPostalCode("122009");
    InMobiSdk.setLogLevel(LogLevel.DEBUG);
    InMobiSdk.setLocationWithCityStateCountry("blore", "kar", "india");
    InMobiSdk.setLanguage("ENG");
    InMobiSdk.setInterests("dance");
    InMobiSdk.setYearOfBirth(1980);
        

    Audio Handling in WKWebView

    For publishers running any audio or video media as the main content, we recommend listening to interruptions by observing AVAudioSessionInterruptionnotification posted by AVAudioSession. This will help preempt any content interruptions and help address user experience issues upfront. For more information read these Apple documents: Article 1, Article 2

    exchange | Android Changelogs

    We are constantly improving the InMobi SDK to ensure that you get the best results on app monetization. The release notes here will give you an overview on all the important changes on InMobi SDK that impact our publishers.

    Note: The changes since December 2018 have been mentioned here. You can always reference the detailed InMobi changelogs here.

    Build 9.0.0 [20/September/2019]

    • Modular SDK

      - Added an ability to integrate Mediation as a separate module.

    • Added support for Android 10
    • Support for Mopub 5.8
    • Interface Changes
      • - APIs added

        AerServTransactionInformation

        public String getCreativeID()

      • - APIs removed
        • InMobiNative

          public InMobiNative(Context context, long placementId, NativeAdListener listener)

          public void setNativeAdListener(NativeAdListener listener)

        • InMobiNative.NativeAdListener
        • InMobiBanner

          public void setListener(BannerAdListener listener)

        • InMobiBanner.BannerAdListener
        • InMobiInterstitial

          public InMobiInterstitial(Context context, long placementId, InterstitialAdListener2 listener)

          public void setInterstitialAdListener(InterstitialAdListener2 listener)

        • InMobiInterstitial.InterstitialAdListener2
    • Bug fixes and performance improvements

    Build 8.2.1 [21/August/2019]

    • Bug Fixes for SDK and AudienceBidder Plugin

    Build 8.2.0 [02/Aug/2019]

    • Chrome Custom tabs support
    • Thread Optimizations
    • Bug Fixes for SDK and AudienceBidder Plugin

    Build 8.1.3 [05/July/2019]

    • Audience Bidder support for DFP
    • Bug Fixes

    Build 8.1.2 [13/Jun/2019]

    • Updated AdColony SDK support to 3.3.10
    • Updated Audience Network (Facebook) support to 5.3.1

    Build 8.1.1 [28/May/2019]

    • Improved Stability with crash fixes
    • Thread and Memory Optimizations
    • Support for new Picasso version 2.71828

    ### API added

    • NativeAdEventListener

    public void onAdReceived(InMobiNative ad)

    Build 8.1.0 [15/May/2019]

    • AudienceBidder
    • Added support for AppNexus
    • Added keyword implementation for MoPub
    • Added DFP plugin

    Build 8.0.9 [24/Apr/2019]

    • Bug fixes

    Build 8.0.8 [17/Apr/2019]

    • Bug fixes

    Build 8.0.7 [05/Apr/2019]

    • Bug fixes
    • Updated AudienceBidder to v1.0.1
    • Support for Amazon Publsiher Service
    • Support for granular keywords
    • Fix issue with updateBid not working with MoPub's refresh
    • Replaced source file with a aar
    • Change in API (see documentation)

    Build 8.0.5 [11/Mar/2019]

    • Added InMobi's Audience Bidder for MoPub
    • Update support for the following mediation adapters
    • AdColony SDKv 3.3.7
    • AdMob SDKv 17.1.1
    • AppLovin SDKv 9.1.0
    • AppNext SDKv 2.4.4.472
    • Audience Network (Facebook) SDKv 5.1.0
    • Chartboost SDKv 7.3.1
    • Flurry (Yahoo) SDKv 11.4.0
    • MoPub SDKv 5.4.1
    • MyTarget SDKv 5.3.1
    • Oath (AOL) SDKv 6.8.2
    • Unity SDKv 3.0.0
    • Vungle SDKv 6.3.24
    • Deprecated Tremor support
    • Deprecated Flurry (Yahoo) Banner
    • Added support for additional reporting for AppLovin and Chartboost
    • Bug fixes

    Build 8.0.1 [28/Nov/2018]

    • Bug Fixes

    Build 8.0.0 [17/Oct/2018]

    • Unification of InMobi SDK and AerServ SDK

    Build 7.3.0 [25/July/2019]

    • Bug fixes.

    Build 7.2.9 [10/July/2019]

    • Removal of createCalendar API from Mraid.
    • Support for new Picasso version 2.71828.
    • Bug fixes.

    ### Interface changes

    • API added:
    • InMobiNative

    public Boolean isVideo()

    Build 7.2.8 [6/May/2019]

    • Bug fixes.

    ### Interface changes

    • API added:
    • NativeAdEventListener

    public void onAdReceived(InMobiNative ad)

    Build 7.2.7 [25/Feb/2019]

    • MMA SDK Integration (China only)
    • Gif Enhancements

    ### Interface changes

    • Deprecated API:
    • InMobiNative

    public static void requestAd(Context context, final InMobiAdRequest adRequest,

    NativeAdRequestListener listener)

    • InMobiBanner

    public static void requestAd(Context context, final InMobiAdRequest adRequest,

    BannerAdRequestListener listener)

    • InMobiInterstitial

    public static void requestAd(Context context, InMobiAdRequest adRequest,

    InterstitialAdRequestListener interstitialAdRequestListener)

    Build 7.2.6 [8/Feb/2019]

    • Bug fix - Avoid crash in WebView processing.

    Build 7.2.4 [14/Dec/2018]

    • Bug fix - Release resource for failures with multiple banners in single AdContainer.

    exchange | iOS Changelogs

    We are constantly improving the InMobi SDK to ensure that you get the best results on app monetization. The release notes should here will give you an overview on all the important changes on InMobi SDK that impact our publishers.

    Note: The changes since December 2018 have been mentioned here. You can always reference the detailed InMobi changelogs here.


    Build 9.0.0 [20/Sept/2019]

    - Changes to support iOS 13

    - New and improved Modularised SDK design

    - Add InMobiMediationSDK.framework to your project for AerServ Mediation.

    - Addressing issue with layering of FAN banners upon refresh

    - SKStoreProductViewController crash fix.

    - Removed Support for iOS 8.

    - Removed Support for AerServ Native ad format.

    - Removed UIWebView from InMobi SDK. Viewability Partners might be using it.

    - Size reduction for both Framework and ipa inflation.

    - Various Bug Fixes and performance improvements

    - Adapter updates for the following mediation partners:

    • MoPub - v5.9.0
    • Google Mobile Ads - v7.50.0

    - APIs Added

    • IMBanner Class + -(void)cancel;
    • IMInterstitial Class + -(void)cancel;
    - APIs Added
    • ASAdView Class
      - @property (nonatomic, assign) ASEnvironmentType env;
      - @property (nonatomic, assign) ASPlatformType platform;
      - @property (nonatomic, assign) BOOL isMuted;
      - @property (nonatomic, assign) BOOL outlineAd;
      - @property (nonatomic, assign) BOOL sizeAdToFit;
      - @property (nonatomic, assign) BOOL useHeaderBidding;
      - @property (nonatomic, strong) NSArray* keyWords;
      - @property (nonatomic, assign) BOOL allowAdvertiserCloseButton;
      - -(void)forceRefreshAd;
      - -(CGSize)adContentSize;
      - -(void)rotateToOrientation:(UIInterfaceOrientation)newOrientation;
      - -(void)play;
      - -(void)pause;

    • ASAdViewDelegate Protocol
      - -(void)willLeaveApplicatonFromAd:(ASAdView*)adView;
      - -(void)adSizeChanged:(ASAdView*)adView;
      - -(void)adView:(ASAdView*)adView didFireAdvertiserEventWithMessage:(NSString*)msg;

    • ASInterstitialViewController Class
      - @property (nonatomic, assign) ASEnvironmentType env;
      - @property (nonatomic, assign) ASPlatformType platform;
      - @property (nonatomic, assign) BOOL isMuted;
      - @property (nonatomic, assign) BOOL showOutline;
      - @property (nonatomic, assign) BOOL useHeaderBidding;
      - -(void)play;
      - -(void)pause;
    • ASInterstitialViewControllerDelegate Protocol
      - -(void)interstitialViewControllerAdInteraction:(ASInterstitialViewController*)viewController;
      - -(void)interstitialViewController:(ASInterstitialViewController*)viewController didFireAdvertiserEventWithMessage:(NSString*)msg;

    Build 8.2.0 [16/July/2019]

    - TRC Removal

    - Caching Removal

    - Mraid Viewable Definition Change

    - Bug fixes

    Build 8.1.2 [16/July/2019]

    - Audience bidding support for DFP

    - SDK size Reduction

    - New api to set slot size for Banner in Audience Bidding

    - Bug fixes

    Build 8.1.1 [13/June/2019]

    - Adapter updates for the following mediation partners:

    • AdColony - 3.3.8
    • Facebook - 5.3.2

    - Bug fixes

    Build 8.1.0 [09/May/2019]

    - Audience bidding support for AppNexus

    - Added bid response support for Audience bidding

    - Added DFP Custom Event support

    - Bug fixes

    Build 8.0.8 [17/April/2019]

    - Addressing issue with layering of FAN banners upon refresh

    Build 8.0.7 [09/April/2019]

    - Audience bidding support for APS

    - Additional support for higher granularity keywords

    Build 8.0.5 [11/Mar/2019]

    - Audience bidding support for MoPub

    - Adapter updates for the following mediation partners:

    • AdColony - 3.3.6
    • AppLovin - 6.1.4
    • Chartboost - 7.3.0
    • Facebook - 5.1.0
    • Flurry - 9.2.3
    • MoPub - 5.4.1
    • MyTarget - 4.8.8
    • Vungle - 6.3.2
    • OneMobile AOL (Millennial Media) - 6.8.2
    • Vungle - 6.3.2
    • Unity - 3.0.0

    - Deprecated Tremor support

    - Deprecated Flurry banner support

    - Added support for additional reporting for AppLovin and Chartboost

    - Bug fixes

    - Google open auction support

    Build 8.0.2 [12/Dec/2018]

    - Mediation bug fixes

    Build 8.0.1 [21/Nov/2018]

    - Added mediation support

    - Bug fixes

    Build 8.0.0 [17/Oct/2018]

    - Added OMSDK support

    - Unification of InMobi and AerServ SDK

    Build 7.3.1 [11/July/2019]

    - Google open auction support

    Build 7.3.0 [27/Jun/2019]

    - Bug Fixes and Optimization

    Build 7.2.9 [28/May/2019]

    - Bug Fixes

    Build 7.2.8 [30/Apr/2019]

    • - Framework size reduction
    • - Bug Fixes
    • - APIs Added
    • * IMNative Class
    • + -(void)nativeAdIsAvailable:(IMNative*)native;

    Build 7.2.7 [26/Feb/2019]

    • - Support for MMA Viewability in China
    • - Bug Fixes

    Build 7.2.4 [21/Jan/2019]

    - Bug Fixes

    Build 7.3.1 [11/July/2019]

    - Google open auction support

    Build 7.3.0 [27/Jun/2019]

    - Bug Fixes and Optimization

    Build 7.2.9 [28/May/2019]

    - Bug Fixes

    Build 7.2.8 [30/Apr/2019]

    • - Framework size reduction
    • - Bug Fixes
    • - APIs Added
    • * IMNative Class
    • + -(void)nativeAdIsAvailable:(IMNative*)native;

    Build 7.2.7 [26/Feb/2019]

    • - Support for MMA Viewability in China
    • - Bug Fixes

    Build 7.2.4 [21/Jan/2019]

    - Bug Fixes

    exchange | Swift Reward test

    Rewarded Video ads are short (15 sec), non-skippable HD videos, which a user opts-in to watch in exchange for rewards like virtual goods or in-game gifts. Preferred by acquisition and brand marketers, these are perfect for integrating in shop fronts, start of gameplay or end of gameplay and help increase the retention of the non paying users. With the reward action dependent only on completed video views, rewarded video ads provide high quality engaged users to advertisers and high eCPMs to publishers.

    Follow these simple steps and start monetizing with Rewarded Video ads:

    Setting up a Rewarded Video Ad

    After adding your app, select REWARDED VIDEO to create a placement for ad type Rewarded video.

    Once you select the placement type as rewarded video, you will be presented with the following.

    You can fill in the key value pair for reward details. SDK will provide this dictionary as a JSON string through a delegate method called interstitial(_ interstitial: IMInterstitial!, rewardActionCompletedWithRewards rewards: [AnyHashable : Any]!) when the video play has ended. You can also choose to handle these rewards completely at your end.

    Creating a Rewarded Video Ad

    Rewarded Video ads use IMInterstitial Class. The IMInterstitial is simply a UIViewController subclass displaying full screen ads that respond to user touch.

    Follow these steps to create the rewarded video ad unit programmatically:

    1. Import the headers and declare an interstitial instance in your ViewController.swift file. Your ViewController header file should look like this:
      import UIKit
      import InMobiSDK
      class ViewController: UIViewController, IMInterstitialDelegate {
          var interstitial: IMInterstitial?
      }
      		
    2. Instantiate the interstitial object. Your viewDidLoad method in ViewController.swift file should look like this:
      override func viewDidLoad() {
              super.viewDidLoad()
              interstitial = IMInterstitial.init(placementId: 1446377525790)
              interstitial?.delegate = self
              interstitial?.load()
      }
      		

      Important: Create only one object per placement ID and reuse it for subsequent ad loads.

    3. For ad status callbacks, implement the delegate property of IMInterstitial. The following callbacks are supported:
      /**
           * Notifies the delegate that the ad server has returned an ad. Assets are not yet available.
           * Please use interstitialDidFinishLoading: to receive a callback when assets are also available.
           */
          public func interstitialDidReceiveAd(_ interstitial: IMInterstitial!) {
              NSLog("[ViewController %@]", #function)
          }
          /**
           * Notifies the delegate that the interstitial has finished loading and can be shown instantly.
           */
          public func interstitialDidFinishLoading(_ interstitial: IMInterstitial!) {
              NSLog("[ViewController %@]", #function)
          }
          /**
           * Notifies the delegate that the interstitial has failed to load with some error.
           */
          public func interstitial(_ interstitial: IMInterstitial!, didFailToLoadWithError error: IMRequestStatus!) {
              NSLog("[ViewController %@]", #function)
              NSLog("Interstitial ad failed to load with error %@", error)
          }
          /**
           * Notifies the delegate that the interstitial would be presented.
           */
          public func interstitialWillPresent(_ interstitial: IMInterstitial!) {
              NSLog("[ViewController %@]", #function)
          }
          /**
           * Notifies the delegate that the interstitial has been presented.
           */
          public func interstitialDidPresent(_ interstitial: IMInterstitial!) {
              NSLog("[ViewController %@]", #function)
          }
          /**
           * Notifies the delegate that the interstitial has failed to present with some error.
           */
          public func interstitial(_ interstitial: IMInterstitial!, didFailToPresentWithError error: IMRequestStatus!) {
              NSLog("[ViewController %@]", #function)
          }
          /**
           * Notifies the delegate that the interstitial will be dismissed.
           */
          public func interstitialWillDismiss(_ interstitial: IMInterstitial!) {
              NSLog("[ViewController %@]", #function)
          }
          /**
           * Notifies the delegate that the interstitial has been dismissed.
           */
          public func interstitialDidDismiss(_ interstitial: IMInterstitial!) {
              NSLog("[ViewController %@]", #function)
          }
          /**
           * Notifies the delegate that the interstitial has been interacted with.
           */
          public func interstitial(_ interstitial: IMInterstitial!, didInteractWithParams params: [AnyHashable : Any]!) {
              NSLog("[ViewController %@]", #function)
          }
          /**
           * Notifies the delegate that the user has performed the action to be incentivised with.
           */
          public func interstitial(_ interstitial: IMInterstitial!, rewardActionCompletedWithRewards rewards: [AnyHashable : Any]!) {
              NSLog("[ViewController %@]", #function)
          }
          /**
           * Notifies the delegate that the user will leave application context.
           */
          public func userWillLeaveApplication(from interstitial: IMInterstitial!){
              NSLog("[ViewController %@]", #function)
          }
      		
    4. To show the Interstitial ad, use the following code:
      interstitial?.show(from: self)
      //interstitial?.show(from: self, with:.coverVertical)
      		

      Here are the possible animation types:

      • coverVertical
      • flipHorizontal
      • none

    Important:

    • Make sure that interstitialDidFinishLoading delegate is fired before making a call to show(from viewController: UIViewController!). Otherwise, the error callback interstitial(_ interstitial: IMInterstitial!, didFailToLoadWithError error: IMRequestStatus!) will be fired. Keep listening to the interstitial states to call show only when the ad is fully loaded.
    • Every time an interstitial ad is shown and subsequently dismissed, you will need to invoke interstitial?.load() again. Without this, you won't be able to call show(from viewController: UIViewController!) again.
    • Implement the interstitial(_ interstitial: IMInterstitial!, rewardActionCompletedWithRewards rewards: [AnyHashable : Any]!) method of IMInterstitialDelegate to detect video completion. If you have specified rewards on the InMobi portal, you can access the JSON dictionary here.

    Retrieving CreativeID

    At times, there are rogue advertisers who escape all the ad quality checks and end up compromising the user experience on the app by showcasing either an irrelevant, distasteful or disrupting creative to the user. To combat such situations, you can retrieve the creativeID of the ad instance and report back to your InMobi point of contact with the encrypted creativeID.

    mInterstitialAd.creativeId //mInterstitialAd is an example instance.

    Testing the Integration

    1. Configure the test mode on InMobi portal.

      Go to Tools - Diagnostics and switch Test Mode to either Global ON or Selective ON.

      If you are integrating an ad unit for the first time Set Test Mode to Global ON.
      If you want to selectively turn on test traffic for a set of devices·

      You already have a prior version of the SDK integrated for this particular ad unit and therefore you should restrict your testing to only few devices
      Set Test Mode to Selective ON.

      In the device section:

      1. In the Device ID box, type the device ID.
      2. In the Device Name box, set any name.
      3. Click Add Device to add the test device.

      If you already have a device configured, you can select the device and test mode will be enabled.

      Note: You MUST turn off the test mode before going live or else your app will fail to monetize.

      Now you are all set to get test ads.

      Getting the Device ID

      The device id is basically the IDFA or IFA (Identifier for Advertising). To get device ID, the easiest approach is to set the log level of the SDK to “debug”. To enable debug logs, add this to didFinishLaunchingWithOptions method within the AppDelegate.swift file, as shown below:

      func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
              //Initialize InMobi SDK with your account ID
              IMSdk.initWithAccountID("Insert InMobi account ID here")
              IMSdk.setLogLevel(.debug)
              // Do your stuff.
              return true
          }
      		

      In the debug mode, the device ID will be logged on XCode developer console as: “Publisher device ID is <device-id>”

      You can enter this device id in the Device ID box.

    2. You will also get feedback on the diagnostics tab on the ad unit and ad request and this can be particularly helpful during integration.

    3. You should also see these key InMobi SDK logs in console when a rewarded video ad is successfully loaded:

      [InMobi] InMobi SDK initialized with account id: <your account id here>

      [InMobi] Fetching interstitial ad for placement id: <your placement id here>

      [InMobi] Publisher device id is <device id here>

      [InMobi] Interstitial ad successfully fetched for placement id: <your placement id here>

    4. Now you would also see the InMobi test ads on your application.
    5. If the SDK is not initialised correctly before creating an ad, you would typically see these logs :

      ** ERROR ** [InMobi] ___ Please initialize the SDK before creating a <ad format> ad.

      ** ERROR ** [InMobi] ___ Account id cannot be null or empty. Please provide a valid Account id.

      [InMobi] Invalid account id passed to init. Please provide a valid account id.

    The complete set of key logs are documented in the following tables.

    SDK Initialization

    Scenario Log Level Logs
    Publisher passed null or empty account id Error Account id cannot be null or empty. Please provide a valid Account id.
    Publisher passed a valid account id Debug InMobi SDK initialized with account id: <account id>
    Publisher passed an invalid account Id Error Invalid account id passed to init. Please provide a valid account id.
    Newer version of SDK is available Debug A newer version (ver. 9.0.0) of the InMobi SDK is available! You are currently on an older version (ver. 5.3.1). Download the latest InMobi SDK from http://www.inmobi.com/products/sdk/#downloads

    Ads Common

    Scenario Log Level Logs
    Ad requested when no network available Error Network not reachable currently. Please try again.
    Ad requested when ad state is loading or available Error An ad load is already in progress. Please wait for the load to complete before requesting for another ad (Placement id :<placement id> ).
    Ad requested when ad is viewed by user Error An ad is currently being viewed by the user. Please wait for the user to close the ad before requesting for another ad (Placement id : <placement id> ).
    Publisher device Id Debug Publisher device id is <Device Id>

    Rewarded Video Ads

    Scenario Log Level Logs
    Publisher created a interstitial without initializing the SDK Error Please initialize the SDK before creating a interstitial ad
    Publisher created a interstitial with an invalid placement id Error Please provide a valid placement id to create a interstitial ad
    Publisher called load on an interstitial Debug Fetching an interstitial ad for placement id: <placement id>
    Successfully fetched ad Debug Interstitial ad successfully fetched for placement id: <placement id>
    Failed to fetch the ad Error Failed to fetch Interstitial ad for placement id:<Placement id> with error:<Status code / message>
    Started loading the interstitial in a webview Debug Started loading Interstitial ad markup in the webview for placement id: <Placement id>
    Interstitial successfully loaded in the webview Debug Successfully loaded Interstitial ad markup in the webview for placement id: <placement id>
    Failed to load interstitial in the webview Error Failed to load the Interstitial markup in the webview for placement id: <placement id>
    Interstitial Ad displayed Debug Successfully displayed Interstitial for placement id:<placement id>
    Interstitial Ad dismissed Debug Interstitial ad dismissed for placement id:<placement id>
    Ad show before ready Show ad before it's ready Error Ad Load is not complete. Please wait for the Ad to be in a ready state before calling show
    Full screen ad cannot be displayed without a view controller. Please pass a view controller to present the full screen ad. Error Full screen ad cannot be displayed without a view controller. Please pass a view controller to present the full screen ad.

    exchange | Swift Full test

    Full-screen video ads are short (15-30 sec), skippable videos, which help in monetization with high eCPMs. Preferred by brands and game developers, these are perfect for happy moments such as level wins and wait times in Player vs Player (PVP). Video ads leverage the power of sight, sound, and motion to create immersive experiences for the user thereby enhancing the in-app ad experience.

    To create a video ad, you need to use an interstitial ad placement. On creating an interstitial ad placement you will find controls on the InMobi portal to either run a mix of static and video ads OR 100% video ads only.

    You also have access to advanced video controls on whether you want to run skippable video ads and only when the user is on Wifi.

    Follow these simple steps and start monetizing with Video ads:

    Setting up a Full-screen Video Ad

    After adding your app, select INTERSTITIAL to create a placement for ad type Interstitial.

    Once you create the Interstitial placement, you will have the placement id.

    Creating a Full-screen Video Ad

    The IMInterstitial is simply a UIViewController subclass displaying full screen ads that respond to user touch.

    Follow these steps to create the interstitial ad unit programmatically:

    1. Import the headers and declare an interstitial instance in your ViewController.swift file. Your ViewController header file should look like this:
      import UIKit
      import InMobiSDK
      class ViewController: UIViewController, IMInterstitialDelegate {
          var interstitial: IMInterstitial?
      }
      		
    2. Instantiate the interstitial object. Your viewDidLoad method in ViewController.swift file should look like this:
      override func viewDidLoad() {
              super.viewDidLoad()
              interstitial = IMInterstitial.init(placementId: 1446377525790)
              interstitial?.delegate = self
              interstitial?.load()
      }
      		

      Important: Create only one object per placement ID and reuse it for subsequent ad loads.

    3. For ad status callbacks, implement the delegate property of IMInterstitial. The following callbacks are supported:
      /**
           * Notifies the delegate that the ad server has returned an ad. Assets are not yet available.
           * Please use interstitialDidFinishLoading: to receive a callback when assets are also available.
           */
          public func interstitialDidReceiveAd(_ interstitial: IMInterstitial!) {
              NSLog("[ViewController %@]", #function)
          }
          /**
           * Notifies the delegate that the interstitial has finished loading and can be shown instantly.
           */
          public func interstitialDidFinishLoading(_ interstitial: IMInterstitial!) {
              NSLog("[ViewController %@]", #function)
          }
          /**
           * Notifies the delegate that the interstitial has failed to load with some error.
           */
          public func interstitial(_ interstitial: IMInterstitial!, didFailToLoadWithError error: IMRequestStatus!) {
              NSLog("[ViewController %@]", #function)
              NSLog("Interstitial ad failed to load with error %@", error)
          }
          /**
           * Notifies the delegate that the interstitial would be presented.
           */
          public func interstitialWillPresent(_ interstitial: IMInterstitial!) {
              NSLog("[ViewController %@]", #function)
          }
          /**
           * Notifies the delegate that the interstitial has been presented.
           */
          public func interstitialDidPresent(_ interstitial: IMInterstitial!) {
              NSLog("[ViewController %@]", #function)
          }
          /**
           * Notifies the delegate that the interstitial has failed to present with some error.
           */
          public func interstitial(_ interstitial: IMInterstitial!, didFailToPresentWithError error: IMRequestStatus!) {
              NSLog("[ViewController %@]", #function)
          }
          /**
           * Notifies the delegate that the interstitial will be dismissed.
           */
          public func interstitialWillDismiss(_ interstitial: IMInterstitial!) {
              NSLog("[ViewController %@]", #function)
          }
          /**
           * Notifies the delegate that the interstitial has been dismissed.
           */
          public func interstitialDidDismiss(_ interstitial: IMInterstitial!) {
              NSLog("[ViewController %@]", #function)
          }
          /**
           * Notifies the delegate that the interstitial has been interacted with.
           */
          public func interstitial(_ interstitial: IMInterstitial!, didInteractWithParams params: [AnyHashable : Any]!) {
              NSLog("[ViewController %@]", #function)
          }
             /**
           * Notifies the delegate that the user will leave application context.
           */
          public func userWillLeaveApplication(from interstitial: IMInterstitial!){
              NSLog("[ViewController %@]", #function)
          }
      		
    4. To show the Interstitial ad, use the following code:
      interstitial?.show(from: self)
      //interstitial?.show(from: self, with:.coverVertical)
      		

      Here are the possible animation types:

      • coverVertical
      • flipHorizontal
      • none

    Important: Make sure that interstitialDidFinishLoading delegate is fired before making a call to show(from viewController: UIViewController!). Otherwise, the error callback interstitial(_ interstitial: IMInterstitial!, didFailToLoadWithError error: IMRequestStatus!) will be fired. Every time an interstitial ad is shown and subsequently dismissed, you will need to invoke interstitial?.load() again. Without this, you won't be able to call show(from viewController: UIViewController!) again.

    Retrieving CreativeID

    At times, there are rogue advertisers who escape all the ad quality checks and end up compromising the user experience on the app by showcasing either an irrelevant, distasteful or disrupting creative to the user. To combat such situations, you can retrieve the creativeID of the ad instance and report back to your InMobi point of contact with the encrypted creativeID.

    mInterstitialAd.creativeId //mInterstitialAd is an example instance.

    Testing the Integration

    1. Configure the Test Mode on InMobi portal.

      Go to Tools - Diagnostics and switch Test Mode to either Global ON or Selective ON.

      If you are integrating an ad unit for the first time Set Test Mode to Global ON.
      If you want to selectively turn on test traffic for a set of devices·

      You already have a prior version of the SDK integrated for this particular ad unit and therefore you should restrict your testing to only few devices
      Set Test Mode to Selective ON.

      In the device section:

      1. In the Device ID box, type the device ID.
      2. In the Device Name box, set any name.
      3. Click Add Device to add the test device.

      If you already have a device configured, you can select the device and test mode will be enabled.

      Note: You MUST turn off the test mode before going live or else your app will fail to monetize.

      Now you are all set to get test ads.

      Getting the Device ID

      The device id is basically the IDFA or IFA (Identifier for Advertising). To get device ID, the easiest approach is to set the log level of the SDK to “debug”. To enable debug logs, add this to didFinishLaunchingWithOptions method within the AppDelegate.swift file, as shown below:

      func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
              //Initialize InMobi SDK with your account ID
              IMSdk.initWithAccountID("Insert InMobi account ID here")
              IMSdk.setLogLevel(.debug)
              // Do your stuff.
              return true
          }
      		

      In the debug mode, the device ID will be logged on XCode developer console as: “Publisher device ID is <device-id>”

      You can enter this device id in the Device ID box.

    2. You will also get feedback on the diagnostics tab on the ad unit and ad request and this can be particularly helpful during integration.

      [InMobi] Fetching interstitial ad for placement id: <your placement id here>

      [InMobi] Publisher device id is <device id here>

      [InMobi] Interstitial ad successfully fetched for placement id: <your placement id here>

    3. Now you would also see the InMobi test ads on your application.
    4. If the SDK is not initialised correctly before creating an ad, you would typically see these logs :

      ** ERROR ** [InMobi] ___ Please initialize the SDK before creating a <ad format> ad.

      ** ERROR ** [InMobi] ___ Account id cannot be null or empty. Please provide a valid Account id.

      [InMobi] Invalid account id passed to init. Please provide a valid account id.

    The complete set of key logs are documented in the following tables.

    SDK Initialization

    Scenario Log Level Logs
    Publisher passed null or empty account id Error Account id cannot be null or empty. Please provide a valid Account id.
    Publisher passed a valid account id Debug InMobi SDK initialized with account id: <account id>
    Publisher passed an invalid account Id Error Invalid account id passed to init. Please provide a valid account id.
    Newer version of SDK is available Debug A newer version (ver. 9.0.0) of the InMobi SDK is available! You are currently on an older version (ver. 5.3.1). Download the latest InMobi SDK from http://www.inmobi.com/products/sdk/#downloads

    Ads Common

    Scenario Log Level Logs
    Ad requested when no network available Error Network not reachable currently. Please try again.
    Ad requested when ad state is loading or available Error An ad load is already in progress. Please wait for the load to complete before requesting for another ad (Placement id :<placement id> ).
    Ad requested when ad is viewed by user Error An ad is currently being viewed by the user. Please wait for the user to close the ad before requesting for another ad (Placement id : <placement id> ).
    Publisher device Id Debug Publisher device id is <Device Id>

    Video Ads

    Scenario Log Level Logs
    Publisher created a interstitial without initializing the SDK Error Please initialize the SDK before creating a interstitial ad
    Publisher created a interstitial with an invalid placement id Error Please provide a valid placement id to create a interstitial ad
    Publisher called load on an interstitial Debug Fetching an interstitial ad for placement id: <placement id>
    Successfully fetched ad Debug Interstitial ad successfully fetched for placement id: <placement id>
    Failed to fetch the ad Error Failed to fetch Interstitial ad for placement id:<Placement id> with error:<Status code / message>
    Started loading the interstitial in a webview Debug Started loading Interstitial ad markup in the webview for placement id: <Placement id>
    Interstitial successfully loaded in the webview Debug Successfully loaded Interstitial ad markup in the webview for placement id: <placement id>
    Failed to load interstitial in the webview Error Failed to load the Interstitial markup in the webview for placement id: <placement id>
    Interstitial Ad displayed Debug Successfully displayed Interstitial for placement id:<placement id>
    Interstitial Ad dismissed Debug Interstitial ad dismissed for placement id:<placement id>
    Ad show before ready Show ad before it's ready Error Ad Load is not complete. Please wait for the Ad to be in a ready state before calling show
    Full screen ad cannot be displayed without a view controller. Please pass a view controller to present the full screen ad. Error Full screen ad cannot be displayed without a view controller. Please pass a view controller to present the full screen ad.

    exchange | Swift Inter test

    Interstitial ads are full page ads placed at natural break points in the app flow. With 10 times the real estate as compared to banner ads, Interstitials are guaranteed to catch your users' eyes and drive higher revenue for your mobile business.

    Follow these steps to start monetizing with Interstitial ads:

    Setting up an Interstitial Ad

    After adding your app, select INTERSTITIAL to create a placement for ad type Interstitial.

    Once you create the Interstitial placement, you will have the placement id.

    Creating an Interstitial Ad

    The IMInterstitial is simply a UIViewController subclass displaying full screen ads that respond to user touch.

    Follow these steps to create the interstitial ad unit programmatically:

    1. Import the headers and declare an interstitial instance in your ViewController.swift file. Your ViewController header file should look like this:
      import UIKit
      import InMobiSDK
      class ViewController: UIViewController, IMInterstitialDelegate {
          var interstitial: IMInterstitial?
      }
      		
    2. Instantiate the interstitial object. Your viewDidLoad method in ViewController.swift file should look like this:
      override func viewDidLoad() {
              super.viewDidLoad()
              interstitial = IMInterstitial.init(placementId: 1446377525790)
              interstitial?.delegate = self
              interstitial?.load()
      }
      		
    3. For ad status callbacks, implement the delegate property of IMInterstitial. The following callbacks are supported:
       /**
           * Notifies the delegate that the ad server has returned an ad. Assets are not yet available.
           * Please use interstitialDidFinishLoading: to receive a callback when assets are also available.
           */
          public func interstitialDidReceiveAd(_ interstitial: IMInterstitial!) {
              NSLog("[ViewController %@]", #function)
          }
          /**
           * Notifies the delegate that the interstitial has finished loading and can be shown instantly.
           */
          public func interstitialDidFinishLoading(_ interstitial: IMInterstitial!) {
              NSLog("[ViewController %@]", #function)
          }
          /**
           * Notifies the delegate that the interstitial has failed to load with some error.
           */
          public func interstitial(_ interstitial: IMInterstitial!, didFailToLoadWithError error: IMRequestStatus!) {
              NSLog("[ViewController %@]", #function)
              NSLog("Interstitial ad failed to load with error %@", error)
          }
          /**
           * Notifies the delegate that the interstitial would be presented.
           */
          public func interstitialWillPresent(_ interstitial: IMInterstitial!) {
              NSLog("[ViewController %@]", #function)
          }
          /**
           * Notifies the delegate that the interstitial has been presented.
           */
          public func interstitialDidPresent(_ interstitial: IMInterstitial!) {
              NSLog("[ViewController %@]", #function)
          }
          /**
           * Notifies the delegate that the interstitial has failed to present with some error.
           */
          public func interstitial(_ interstitial: IMInterstitial!, didFailToPresentWithError error: IMRequestStatus!) {
              NSLog("[ViewController %@]", #function)
          }
          /**
           * Notifies the delegate that the interstitial will be dismissed.
           */
          public func interstitialWillDismiss(_ interstitial: IMInterstitial!) {
              NSLog("[ViewController %@]", #function)
          }
          /**
           * Notifies the delegate that the interstitial has been dismissed.
           */
          public func interstitialDidDismiss(_ interstitial: IMInterstitial!) {
              NSLog("[ViewController %@]", #function)
          }
          /**
           * Notifies the delegate that the interstitial has been interacted with.
           */
          public func interstitial(_ interstitial: IMInterstitial!, didInteractWithParams params: [AnyHashable : Any]!) {
              NSLog("[ViewController %@]", #function)
          }
          /**
           * Notifies the delegate that the user will leave application context.
           */
          public func userWillLeaveApplication(from interstitial: IMInterstitial!){
              NSLog("[ViewController %@]", #function)
          }
      		
    4. To show the Interstitial Ad, use the following code:
      interstitial?.show(from: self)
      //interstitial?.show(from: self, with:.coverVertical)
      		

      Here are the possible animation types:

      • coverVertical
      • flipHorizontal
      • none

    Important:

    • Make sure that interstitialDidFinishLoading delegate is fired before making a call to show(from viewController: UIViewController!). Otherwise, the error callback interstitial(_ interstitial: IMInterstitial!, didFailToLoadWithError error: IMRequestStatus!) will be fired.
    • Every time an interstitial ad is shown and subsequently dismissed, you will need to invoke interstitial?.load() again. Without this, you won't be able to call show(from viewController: UIViewController!) again.

    Retrieving CreativeID

    At times, there are rogue advertisers who escape all the ad quality checks and end up compromising the user experience on the app by showcasing either an irrelevant, distasteful or disrupting creative to the user. To combat such situations, you can retrieve the creativeID of the ad instance and report back to your InMobi point of contact with the encrypted creativeID.

    		public func interstitialDidFinishLoading(_ interstitial: IMInterstitial!) {
            interstitial.creativeId
        }
    	

    Testing the Integration

    1. Configure the test mode on InMobi portal.

      Go to Tools - Diagnostics and switch Test Mode to either Global ON or Selective ON.

      If you are integrating an ad unit for the first time Set Test Mode to Global ON.
      If you want to selectively turn on test traffic for a set of devices·

      You already have a prior version of the SDK integrated for this particular ad unit and therefore you should restrict your testing to only few devices
      Set Test Mode to Selective ON.

      In the device section:

      1. In the Device ID box, type the device ID.
      2. In the Device Name box, set any name.
      3. Click Add Device to add the test device.

      If you already have a device configured, you can select the device and test mode will be enabled.

      Note: You MUST turn off the test mode before going live or else your app will fail to monetize.

      Now you are all set to get test ads.

      Getting the Device ID

      import AdSupport
      let deviceId = ASIdentifierManager.shared().advertisingIdentifier.uuidString
      		

      You can enter this device id in the Device ID box.

    2. You will also get feedback on the diagnostics tab on the ad unit and ad request and this can be particularly helpful during integration.

    3. You should also see these key InMobi SDK logs in console when a interstitial ad is successfully loaded:

      [InMobi] InMobi SDK initialized with account id: <your account id here>

      [InMobi] Fetching interstitial ad for placement id: <your placement id here>

      [InMobi] Publisher device id is <device id here>

      [InMobi] Interstitial ad successfully fetched for placement id: <your placement id here>

    4. Now you would also see the InMobi test ads on your application.
    5. If the SDK is not initialised correctly before creating an ad, you would typically see these logs :

      ** ERROR ** [InMobi] ___ Please initialize the SDK before creating a <ad format> ad.

      ** ERROR ** [InMobi] ___ Account id cannot be null or empty. Please provide a valid Account id.

      [InMobi] Invalid account id passed to init. Please provide a valid account id.

    The complete set of key logs are documented in the following tables.

    SDK Initialization

    Scenario Log Level Logs
    Publisher passed null or empty account id Error Account id cannot be null or empty. Please provide a valid Account id.
    Publisher passed a valid account id Debug InMobi SDK initialized with account id: <account id>
    Publisher passed an invalid account Id Error Invalid account id passed to init. Please provide a valid account id.
    Newer version of SDK is available Debug A newer version (ver. 9.0.0) of the InMobi SDK is available! You are currently on an older version (ver. 5.3.1). Download the latest InMobi SDK from http://www.inmobi.com/products/sdk/#downloads

    Ads Common

    Scenario Log Level Logs
    Ad requested when no network available Error Network not reachable currently. Please try again.
    Ad requested when ad state is loading or available Error An ad load is already in progress. Please wait for the load to complete before requesting for another ad (Placement id :<placement id> ).
    Ad requested when ad is viewed by user Error An ad is currently being viewed by the user. Please wait for the user to close the ad before requesting for another ad (Placement id : <placement id> ).

    Interstitial Ads

    Scenario Log Level Logs
    Publisher created a interstitial without initializing the SDK Error Please initialize the SDK before creating a interstitial ad
    Publisher created a interstitial with an invalid placement id Error Please provide a valid placement id to create a interstitial ad
    Publisher called load on an interstitial Debug Fetching an interstitial ad for placement id: <placement id>
    Successfully fetched ad Debug Interstitial ad successfully fetched for placement id: <placement id>
    Failed to fetch the ad Error Failed to fetch Interstitial ad for placement id:<Placement id> with error:<Status code / message>
    Started loading the interstitial in a webview Debug Started loading Interstitial ad markup in the webview for placement id: <Placement id>
    Interstitial successfully loaded in the webview Debug Successfully loaded Interstitial ad markup in the webview for placement id: <placement id>
    Failed to load interstitial in the webview Error Failed to load the Interstitial markup in the webview for placement id: <placement id>
    Interstitial Ad displayed Debug Successfully displayed Interstitial for placement id:<placement id>
    Interstitial Ad dismissed Debug Interstitial ad dismissed for placement id:<placement id>
    Ad show before ready Show ad before it's ready Error Ad Load is not complete. Please wait for the Ad to be in a ready state before calling show
    Full screen ad cannot be displayed without a view controller. Please pass a view controller to present the full screen ad. Error Full screen ad cannot be displayed without a view controller. Please pass a view controller to present the full screen ad.

    Advanced: InMobi Custom Frames

    Supercharge the full-screen experience by making the most of your in-game assets like characters, themes, and interactions to introduce interstitial ads which look like an extension of your game design.

    Getting Started with Custom Frames

    In order to activate Custom Frames on your interstitial ads, integrate with InMobi Interstitial ads and activate “Custom Frames” while creating the Interstitial placement.

    1. Specify the device you want to target the ad, and then select the orientation of your interstitial ad.
    2. Upload a frame, or select one of the preset frames. Ensure that you comply with the “Custom Frame Specification” mentioned in the section below.
    3. Upload a close button, or select one of the preset close buttons. You can choose the placement of the close button at either the top left or top right corner.
    4. Change the creative size to fit the interstitial ad and modify the placement of the creative using the “Creative Ad Position” to fit the interstitial ad perfectly. Ensure that the creative fits into the inner container of the frame and does not spill out.

    More Details

    Understanding Device Size and Orientation

    InMobi Custom Frames are tied to a particular device size and orientation. This is important because you upload, or select, a specific frame to go with the device size and orientation combination.

    Notes:

    • If you have an app that is usable in both landscape and portrait modes, and you make interstitial ad calls in both modes, you must create two custom frame ad units, one for each landscape and portrait. InMobi will automatically pick the right template based on the ad request orientation.
    • If you use the same placement Id for phones and tablets, you must create separate custom frame ad units for phones and tablets to make sure you can serve interstitial units with custom frames across all devices.
    Understanding InMobi Default Templates

    If you have at least one InMobi Custom Frame, you will see a listing page containing different custom frames, along with their performance metrics. The first item is called InMobi Default. You cannot edit this template, nor can you pause or delete this unit.

    InMobi Default templates are used in two cases:

    • When an incoming ad request and ad combination does not match any custom frame unit created.
    • When InMobi, through its optimization logic, detects that not using a custom frame might actually give better performance. For example, there are certain creatives that will not work with custom frames. In this case, the InMobi Default template is used to make sure that InMobi can render these high eCPM creatives in your ad slot.

    Note: You cannot turn off the InMobi Default template.

    Custom Frame Specification

    Please keep in mind the following when designing custom frames for your interstitial ads:

    • The ad will appear in a transparent area (called the 'inner container') inside the frame.

    • In the image above, the inner container is the section in blue.
      • The inner container must be a rectangular figure with the same aspect ratio as the interstitial ad slot. That is, 2:3 for a 320x480 slot, 8:5 for a 1280x800 slot, and so on.
      • The inner container must be a transparent area.
      • The inner container cannot be less than 70% of the interstitial size. This means that for a 320x480 interstitial slot, the inner container should not be less than 224x336.
      • The inner edges of the frame must not be cluttered. That is, it should not disrupt the inner ad area. Strict rectangular corners, or very slightly rounded corners are allowed.
      • Refer the table below for the sizes supported:
      Device Orientaton Frame Size Inner Container Size

      Smartphone 1

      Portrait

      320x480 (RGB, 72ppi)

      240x360

      Landscape

      480x320 (RGB, 72ppi)

      360x240

      Smartphone 2

      Portrait

      320x568 (RGB, 72ppi)

      250x444

      Landscape

      568x320 (RGB, 72ppi)

      444x250

      Tablet 1

      Portrait

      768x1024 (RGB, 72ppi)

      576x768

      Landscape

      1024x768 (RGB, 72ppi)

      768x576

      Tablet 2

      Portrait

      800x1280 (RGB, 72ppi)

      600x960

      Landscape

      1280x800 (RGB, 72ppi)

      960x600

    • Create the close button on a transparent area with an aspect ratio of 1:1. The allowed sizes are 15x15 px or 40x40 px.

    Notes:

    • Frames and Close buttons must be uploaded in PNG format.
    • Background color and translucency are added by the SDK.

    A/B Testing

    Experiment with custom frames for the same interstitial placement by creating multiple concepts (for example, different colors, different characters, with and without animation, and so on) and distributing exposure across these concepts.

    • When testing new concepts, limit exposure to them to ensure that the monetization potential of your property is not affected. To limit the number of ad impressions served on the new concepts, you can select the Limit Exposure check box.
    • Once you are sure of the performance of the concept, you can uncheck the Limit Exposure check box.

    exchange | Swift Banner test

    Banner Ads are graphical ad, typically including a combination of static/animated images and text designed to convey a marketing message and/or cause the user to take an action. All types of apps can leverage banner ads for monetization.

    Follow these steps to start monetizing with Banner ads:

    Setting up a Banner Ad

    After adding your app, select BANNER AD to create a placement for ad type Banner.

    Once you create the banner placement, you will have the placement id.

    Creating a Banner Ad

    The IMBanner is simply a UIView subclass displaying HTML ads. The InMobi SDK provides two mechanisms to implement a banner ad:

    a. Programmatic Instantiation

    1. Import the frameworks and declare a Banner instance in your ViewController.swift file. Your ViewController header file should look like this:
      import UIKit
      import InMobiSDK
      class ViewController: UIViewController, IMBannerDelegate {
          var banner: IMBanner?
      }
      		
    2. Instantiate the banner object. Your ViewController.m file should look like this:
      override func viewDidLoad() {
              super.viewDidLoad()
              banner = IMBanner.init(frame: CGRect(x: 0, y: 0, width: 320, height: 50), placementId: <Insert your placement ID here>)
              banner?.delegate = self
              self.view.addSubview(banner!)
              banner?.load()
              // Use this API to enable or disable auto refresh
              banner?.shouldAutoRefresh(true)
              // Use this API to set a custom refresh interval on the banner
              banner?.refreshInterval = 90
          }
      		

      By default, IMBanner refreshes after every 60 seconds. You can also set a custom refresh interval or turn off AutoRefresh to manually load ads. For both manual load and Auto Refresh, the minimum time interval between two successive ad loads should be 20 seconds.

      // to turn off auto refresh set the below value to NO.
      [self.banner shouldAutoRefresh:NO];
      //to set custom refresh interval
      [self.banner setRefreshInterval:40];
      		
    3. If at any time you want to release the banner:
       // perform the deinitialization
        banner?.delegate = nil
      banner = nil
      		
    4. For ad status callbacks, implement the delegate methods of IMBannerDelegate. The following callbacks are supported:
      /**
           * Notifies the delegate that the banner has finished loading
           */
          public func bannerDidFinishLoading(_ banner: IMBanner!) {
              NSLog("[ViewController %@]", #function)
          }
          /**
           * Notifies the delegate that the banner has failed to load with some error.
           */
          public func banner(_ banner: IMBanner!, didFailToLoadWithError error: IMRequestStatus!) {
              NSLog("[ViewController %@]", #function)
              NSLog("Banner ad failed to load with error %@", error)
          }
          /**
           * Notifies the delegate that the banner was interacted with.
           */
          public func banner(_ banner: IMBanner!, didInteractWithParams params: [AnyHashable : Any]!) {
              NSLog("[ViewController %@]", #function)
          }
          /**
           * Notifies the delegate that the user would be taken out of the application context.
           */
          public func userWillLeaveApplication(from banner: IMBanner!) {
              NSLog("[ViewController %@]", #function)
          }
          /**
           * Notifies the delegate that the banner would be presenting a full screen content.
           */
          public func bannerWillPresentScreen(_ banner: IMBanner!) {
              NSLog("[ViewController %@]", #function)
          }
          /**
           * Notifies the delegate that the banner has finished presenting screen.
           */
          public func bannerDidPresentScreen(_ banner: IMBanner!) {
              NSLog("[ViewController %@]", #function)
          }
          /**
           * Notifies the delegate that the banner will start dismissing the presented screen.
           */
          public func bannerWillDismissScreen(_ banner: IMBanner!) {
              NSLog("[ViewController %@]", #function)
          }
          /**
           * Notifies the delegate that the banner has dismissed the presented screen.
           */
          public func bannerDidDismissScreen(_ banner: IMBanner!) {
              NSLog("[ViewController %@]", #function)
          }
          /**
           * Notifies the delegate that the user has completed the action to be incentivised with.
           */
          public func banner(_ banner: IMBanner!, rewardActionCompletedWithRewards rewards: [AnyHashable : Any]!){
              NSLog("[ViewController %@]", #function)
          }
      		
    5. You can use the following transitions while refreshing your banner object:
      • none
      • flipFromLeft
      • flipFromRight
      • curlUp
      • curlDown
      banner?.transitionAnimation = .curlUp
      		

    b. Creating a Banner Instance through Interface Builder

    1. Place the UIView in your ViewController’s view at the position where the ad should be displayed.
    2. Set the banner frame.
    3. Set the Class Identity of the UIView to IMBanner.
    4. In your ViewController header file, declare an IBOutlet instance of IMBanner.
    5. Set this as your outlet in your UIView(Banner) in the ViewController Scene in the Storyboard.

    Retrieving CreativeID

    At times, there are rogue advertisers who escape all the ad quality checks and end up compromising the user experience on the app by showcasing either an irrelevant, distasteful or disrupting creative to the user. To combat such situations, you can retrieve the creativeID of the ad instance and report back to your InMobi point of contact with the encrypted creativeID.

    public func bannerDidFinishLoading(_ banner: IMBanner!) {
           bannerAd.creativeId // mBannerAd is an example instance 
        }
    	

    Testing the Integration

    1. Configure the test mode on InMobi portal.

      Go to Tools - Diagnostics and switch Test Mode to either Global ON or Selective ON.

      If you are integrating an ad unit for the first time Set Test Mode to Global ON.
      If you want to selectively turn on test traffic for a set of devices·

      You already have a prior version of the SDK integrated for this particular ad unit and therefore you should restrict your testing to only few devices
      Set Test Mode to Selective ON.

      In the device section:

      1. In the Device ID box, type the device ID.
      2. In the Device Name box, set any name.
      3. Click Add Device to add the test device.

      If you already have a device configured, you can select the device and test mode will be enabled.

      Note: You MUST turn off the test mode before going live or else your app will fail to monetize.

      Now you are all set to get test ads.

      Getting the Device ID

      The device id is basically the IDFA or IFA (Identifier for Advertising). To get device ID:

      import AdSupport
      let deviceId = ASIdentifierManager.shared().advertisingIdentifier.uuidString
      		

      You can enter this device id in the Device ID box.

    2. You will also get feedback on the diagnostics tab on the ad unit and ad request and this can be particularly helpful during integration.

    3. You should also see these key InMobi SDK logs in console when a banner ad is successfully loaded:

      [InMobi] InMobi SDK initialized with account id:

      [InMobi] Loading Banner ad for placement id:

      [InMobi] Banner ad successfully fetched for placement id:

    4. Now you would also see the InMobi test ads on your application.
    5. If the SDK is not initialised correctly before creating an ad, you would typically see these logs :

      ** ERROR ** [InMobi] ___ Please initialize the SDK before creating a <ad format> ad.

      ** ERROR ** [InMobi]

      [InMobi] Invalid account id passed to init. Please provide a valid account id.

    The important set of logs are documented in the following tables.

    SDK Initialization

    Scenario Log Level Logs
    Publisher passed valid account id Debug InMobi SDK initialized with account id:
    Publisher passed an invalid account Id Error Invalid account id passed to init. Please provide a valid account id.
    Newer version of SDK is available Debug A newer version (ver. 9.0.0) of the InMobi SDK is available! You are currently on an older version (ver. 5.3.1). Download the latest InMobi SDK from http://www.inmobi.com/products/sdk/#downloads.

    Ads Common

    Scenario Log Level Logs
    Ad requested when no network available Error Network not reachable currently. Please try again.
    Ad requested when ad state is loading or available Error An ad load is already in progress. Please wait for the load to complete before requesting for another ad (Placement id : ).
    Ad requested when ad is viewed by user Error An ad is currently being viewed by the user. Please wait for the user to close the ad before requesting for another ad (Placement id : ).

    Banner Ads

    Scenario Log Level Logs
    Publisher created a banner without initializing the SDK Error Please initialize the SDK before creating a Banner ad
    Publisher created a banner with an invalid/null placement id Error Please provide a valid placement id to create a Banner ad
    Publisher called load on a banner from IB/xml with improper placement id Error Please provide a valid placement id to create a Banner ad
    Publisher called load on a banner Debug Fetching a Banner ad for placement id: ( )
    Successfully fetched ad Debug Banner ad successfully fetched for placement id: ( )
    Failed to fetch the ad Debug Failed to fetch Banner ad for placement id: ( with error: )
    Started loading the banner in a webview Debug Started loading Banner ad markup in the webview for placement id: ( )
    Banner successfully loaded in the webview Debug Successfully loaded Banner ad markup in the webview for placement id: ( )
    Failed to load banner in the webview Debug Failed to load the Banner markup in the webview for placement id: ( )
    Banner refresh is initiated Debug Initiating Banner refresh for placement id: ( )

    exchange | Swift test

    Getting Started with iOS Integration

    You can get started with the following:

    The latest version of InMobi SDK supports iOS 10.0 and later. Also, this version of iOS SDK requires XCode 10.9 and later.

    Note: We recommend to call all InMobi APIs on main thread.

    Version 9.0.0 7.4.0
    Size (.IPA Inflation) 691 KB TBA
    SDK Links

    Step 1: Adding the SDK to your Project

    Option 1: Integration via Cocoapods

    1. If you are not already using Cocoapods, go to your Xcode project directory and create a pod file using the command below.
      pod init
      				
    2. Add the following to Podfile.
      pod 'InMobiSDK'
      				
    3. Once you have added it to the pod file, run the command below to complete the task for dependency. You now have a workspace with the pods.
      pod install
      				

    Option 2: Integrating the framework directly

    Alternatively, you can integrate the framework directly.

    1. Add the following MANDATORY frameworks to your Xcode project:

    • InMobiSDK.framework from the downloaded InMobi iOS SDK bundle
    • libsqlite3.0.tbd
    • libz.tbd
    • WebKit.framework

    2. Add -ObjC flag to the Other Linker Flags:

    1. Open your project in Xcode.
    2. Select Application Target > Build Settings.
    3. In the Search box, search for Other Linker Flags.
    4. Add the -ObjC flag

    Important Prerequisites:

    Let’s pause for some checks before we begin initializing the SDK:

    Checkpoint 1: Preparing your App for iOS 10

    App Transport Security (ATS), a default setting introduced with iOS 9 that mandates apps to make network connections only over TLS version 1.2 and later. Though InMobi is committed towards the adoption of HTTPS, the current setup requires our demand partners to support this change and be 100% compliant with all the requirements of ATS.

    While we work with our partners progressing towards a secure environment, to ensure ads work on iOS 9 and later versions, you need to follow these steps as a near-term fix:

    • Disable ATS (Recommended) - to ensure non-secure content from the partners work correctly in your updated apps. To disable ATS flag, add the following code snippet to your app's Info.plist.

      <key>NSAppTransportSecurity</key>
      <dict>
      <key>NSAllowsArbitraryLoads</key>
      <true/>
      </dict>
      				
    • Disable ATS with exceptions (Not Recommended) - if you plan to migrate towards ATS compliance. You can achieve so by allowing secure content from your domains by adding them on the exception list.
      <key>NSAppTransportSecurity</key>
      <dict>
      <key>NSAllowsArbitraryLoads</key>
      <true/>
      <key>NSExceptionDomains</key>
      <dict>
      <key>example.com</key>
      <dict>
      <key>NSIncludesSubdomains</key>
      <true/>
      </dict>
      </dict>
      </dict>
      				

    Remember: Refrain from using InMobi domains and CDN in the exception list as it will result in errors during the runtime.

    Checkpoint 2: iOS 12 WiFi Settings

    Apple has introduced privacy settings to access WiFi details from iOS 12 onwards. To boost monetization and relevant user experience, we encourage sharing WiFi details for targeted advertising.

    1. Enable ‘Access WiFi Information’ on your App ID.

    2. Enable access ‘Access WiFi Information’ for your target app from XCode capabilities.

    3. Ensure WiFi Access is added to your App.entitlements file.

    Note:Please ask the user for location consent. Here is how how to do that.

    Step 2: Initializing the SDK

    Step 2.1 Import the InMobi SDK header in your AppDelegate.h file:

    @import InMobiSDK;
    /**Please do not remove the window property as it can lead to undefined behavior**/
    // var window: UIWindow;
    			

    Step 2.2 Initialize the SDK in the didFinishLaunchingWithOptions method within the app delegate's .m file:

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
            /*
             * Enable logging for better debuggability. Please turn off the logs before submitting your App to the AppStore
             */
            IMSdk.setLogLevel(IMSDKLogLevel.debug)
            /*
             * Initialize the InMobi SDK immediately after the app launches.
             *
             * For EU Region use the following init api to pass user consent for data collection, for GDPR Compliance.
             */
            let conscentDict: NSDictionary = [IM_GDPR_CONSENT_AVAILABLE : "true"]
            IMSdk.initWithAccountID(INMOBI_ACCOUNT_ID, consentDictionary:conscentDict as? [AnyHashable : Any])
            return true
        }
    			

    Let’s understand a few things here before you proceed:

    What is a consentObject? - A consentObject is a dictionary representation of all kinds of consent provided by the publisher to the SDK. The key is mandatory if you wish to monetize traffic from EEA region. You can read further on GDPR regulations here.

    Key Type Inference
    gdpr_consent_available String "true" : User has provided consent to collect and use data.

    "false": User has not provided consent to collect and use data.

    Any value other than “true” and “false” is invalid and will be treated as value not provided by user.

    The key, gdpr_consent_available can be accessed via string constant IM_GDPR_CONSENT_AVAILABLE.

    gdpr String Whether or not the request is subjected to GDPR regulations (0 = No, 1 = Yes), omission indicates Unknown.

    Important note on consentObject:

    1. consentObject has to be provided in every session. SDK does not persist consent, it only keeps the consentObject in memory. If the app is relaunched, SDK will lose the consentObject.
    2. Within a session, consentObject can be updated as below:
      [IMSdk updateGDPRConsent:@{<Insert consentObject dictionary here>}];
      				
    3. As part of the General Data Protection Regulation (“GDPR”) publishers who collect data on their apps, are required to have a legal basis for collecting and processing the personal data of users in the European Economic Area (“EEA”). Please ensure that you obtain appropriate consent from the user before making ad requests to InMobi for Europe and indicate the same by following our recommended SDK implementation. Please do not pass any demographics information of a user; if you do not have user consent from such user in Europe.

    Note: You can locate your account ID from the account interface as shown in the image below:

    Step 2.3 | Pass the location information to allow better ad targeting

    Recommended: If your app collects location from the user, we recommend passing it up, as impressions with location signal have higher revenue potential. InMobi SDK will automatically pass the location signals if available in the app. If you use location in your app, but would like to disable passing location signals to InMobi, then TURN OFF the “Location Automation” for your property on the InMobi dashboard.

    Otherwise: You can set NSLocationWhenInUseUsageDescription flag (description for asking location permission) in your info.plist file.

    self.locationManager = CLLocationManager()
    self.locationManager.requestWhenInUseAuthorization()
    self.locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters
    self.locationManager.delegate = self
    self.locationManager.startUpdatingLocation()
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
            if let currentLocation = locations.last {
                IMSdk.setLocation(currentLocation);
                self.locationManager.stopUpdatingLocation();
            }
        }
    			

    Step 2.4 Pass age and gender information to allow better ad targeting. Ensure that you have user consent to share this data. The following values are supported:

    Age Gender
    • below18
    • between18And24
    • between25And29
    • between30And34
    • between35And44
    • between45And54
    • between55And65
    • Above65
    • male
    • female

    Example:

    IMSdk.setGender(.male)
    IMSdk.setAgeGroup(.between25And29)
    			

    Note:

    Note: Audio Handling in WKWebView

    For publishers running any audio or video media as the main content, we recommend listening to interruptions by observing AVAudioSessionInterruptionnotification posted by AVAudioSession. This will help preempt any content interruptions and help address user experience issues upfront. For more information read these Apple documents: Article 1, Article 2.

    You are all set now! Let’s now have a look at how you can set up different ad formats and begin monetizing. Ready?

    exchange | Swift Native test

    InMobi Native ads seamlessly blend in with your app’s content, maximizing user engagement without compromising on user experience. You can choose and customize the layout that best matches the design of your app. It is ideal for news, utility and communication apps.

    InMobi Native Ads can have video and/or static image both. Depending on the placement you can opt for:

    • In-Feed Ad - a muted autoplay HD video or a simple static image ad.
    • Splash Ad - blends in the launch screen of apps and monetize user time when the app is loading in the background. These ads can also be a muted autoplay HD video ad or a simple static image ad.

    Static Feed Ad

    InFeed Video Ad

    Splash Video Ad

    Follow these simple steps and start monetizing with Native ads:

    Setting up a Native Ad Placement

    1. Create a Native Content placement.

    2. In-Feed Video Ad Placement

      1. Select FEED as the Native Ad Layout.
      2. For In-Feed Video, select either of the aspect ratio 256:135 or 16:9. Both the aspect ratios will have default static native fallback enabled with similar aspect ratio.


      Static Feed Ad Placement

        Select FEED as the Native Ad Layout.

      Splash Video Ad Placement

      • Select SPLASH as the Native Ad Layout.

      • Select the desired aspect ratio. Default value for the aspect ratio will be 9:16.

      Others (China only)

      • Select Others as the Native Ad Layout.

      • Select aspect ratio 16:9. This will have default static native fallback enabled with similar aspect ratio.
      • A new sub field is added in Others layout called Native Layout Type. It has the following values: “Native Interstitial”, “Native Page”, “Native Banner”, “Native Focus”, “Native Lock Screen”, “Native Other”.
      • Default value will be Native Interstitial in Native layout type field.

      Pre-Roll Ad Integration

      • Select Pre-roll as the Native Ad Layout.

      • Save the Pre-roll native placement layout.

    Native Ad APIs

    The IMNative Class contains the following objects:

    • NSString* adTitle - Returns the title for the ad.
    • NSString* adDescription - Returns the description for the ad.
    • UIImage* adIcon - Returns icon image for the ad.
    • NSString* adCtaText - Returns click to action text for the ad.
    • NSString* adRating - Returns rating for the ad (optional).
    • NSURL* adLandingPageUrl - Returns landing URL for the ad.
    • BOOL isAppDownload - Returns whether the ad is for downloading an app.
    • NSString* customAdContent - This will have additional information (description, image URL, etc.), which can be used to create custom UI around the primary view of ad.

    The IMNative Class supports the following functions:

    • -(UIView*)primaryViewOfWidth:(CGFloat)width - Returns a UIView of specified width. This is the main ad content in your native ad. It will return a view of the same aspect ratio that you selected on the InMobi dashboard while creating the native placement. All impression render events are also fired automatically when this primary view is displayed on the screen.

      If you have selected Feed Layout while creating your placement, specify width = 25 while fetching your primaryView. It will just show the AdChoices Icon and fire the ad render events.

    • -(void)load - Function to load an ad into memory.
    • -(BOOL)isReady - True implies that the ad is ready to be displayed.
    • -(void)reportAdClickAndOpenLandingPage - This function fires the click events and opens the landing page. You need not open landing page on your own while using this function.
    • -(void)recyclePrimaryView - Call this function whenever the ad goes out of the visible area on the screen. Also, call this before loading a native ad again on the same object.

    In-Feed Ad Integration

    1. Import the InMobi SDK header files.
      #import <InMobiSDK/InMobiSDK.h>
      		
    2. Declare an ad position in your feed where you want to show ad. Example is to show ad at 4th position.
      #define IM_AD_INSERTION_POSITION 4
      		
    3. Declare a native Ad instance in your ViewController.m
      @interface TableViewController () <IMNativeDelegate>
      @property(nonatomic,strong) IMNative *InMobiNativeAd;
      @end
      		
    4. Your final ViewDidLoad Code should look like:
      override func viewDidLoad() {
          super.viewDidLoad()
          InMobiNativeAd = IMNative(placementId: <Insert InMobi placement ID here>);
          InMobiNativeAd?.delegate = self;
          InMobiNativeAd?.load()
             // Your app content 
      }
      		
    5. Implement IMNativeDelegate methods for the success callback. The success callback indicates that the ad is ready to be shown on the screen. Here you should add the InMobiNativeAd Object to your TableView's data source.
      func nativeDidFinishLoading(_ native: IMNative!) {
           self.tableData.insert(native, at: IM_AD_INSERTION_POSITION)
           self.tableView.reloadData()
           NSLog("InMobi Native Did finished loading");
          }
      		
    6. Rendering native ads and impression tracking

      You have successfully received a native ad when you get the callback nativeAdDidFinishLoading. The following example shows how to fetch the adView in your tableView delegate cellForRowAtIndexPath.

      Note: Impression events will be fired only when the Native Ad's primary view is in visible area of the screen.

      Implement the below custom cell class using storyboard.

      class InFeedTableViewCell: UITableViewCell {
          @IBOutlet var iconImage : UIImage?
          @IBOutlet var titleLabel : UILabel?
          @IBOutlet var subtitleLabel : UILabel?
          @IBOutlet var descriptionLabel : UILabel?
          @IBOutlet var ctaLabel : UILabel?
          @IBOutlet var adView : UIView?
      }
      		
      func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath:
              NSIndexPath) -> UITableViewCell {
              var cell = (tableView.dequeueReusableCell(withIdentifier: "InFeedTableCell")! as! InFeedTableViewCell)
              if let nativeAd = self.tableData?.object(at: indexPath.row) {
                  if nativeAd is IMNative {
                      var currentNativeAd : IMNative = nativeAd
                      cell.iconImageView.image! = currentNativeAd.adIcon
                      cell.titleLabel!.text! = currentNativeAd.adTitle
                      cell.subtitleLabel?.text! = "Sponsored"
                      cell.descriptionLabel.text! = currentNativeAd.adDescription
                      cell.ctaLabel.text! = currentNativeAd.adCtaText
                      //Calculate your feed’s primaryImageViewWidth and use it to fetch and Ad Primary view of same width.
                      var AdPrimaryViewOfCorrectWidth =
                          currentNativeAd.primaryViewOfWidth(primaryImageViewWidth)
                      AdPrimaryViewOfCorrectWidth.frame = primaryImageViewFrame
                      cell.addSubview(AdPrimaryViewOfCorrectWidth)
                      var singleTapAndOpenLandingPage = UITapGestureRecognizer(target:
                          currentNativeAd, action: #selector(self.reportAdClickAndOpenLandingPage))
                      cell.ctaLabel.userInteractionEnabled = true
                      cell.ctaLabel.addGestureRecognizer(singleTapAndOpenLandingPage)
                  }
              }
              else {
                  // Your app's Table Cell implementations
              }
              return cell;
          }
      		
    7. You need to recycle the Native Ad's Primary view, every time your ad goes out of the screen area. This is to optimize memory usage as well as ensuring that the AdView does not conflict with your app’s native views. Call recyclePrimaryView method on the InMobiNativeAd object every time the ad goes out of the visible area. In a TableView, this can be called in the didEndDisplayingCell Method:
      override func tableView(tableView: UITableView, didEndDisplayingCell cell:  
         UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
              if let nativeAd = self.tableData?.object(at: indexPath.row) {
      if nativeAd is UIView {
                  self.InMobiNativeAd.recyclePrimaryView()
              }
             }
          }
      		

      Note: After calling the recyclePrimaryView, if you want to add the view again on the screen, you must fetch it from [self.InMobiNativeAd primaryViewOfWidth:<custom width>] as the previous view would have been recycled. If you have added it in the cellForRowAtIndexPath delegate (as mentioned in step 8), you don’t have to do anything here.

    8. Refreshing the ad - You will need to refresh the ad at various points to optimize ad exposure to your users. To refresh the ad, you will need to call the following functions in the same order.

      Note: It is important to remove the IMNative object from your tableData and destroy the current ad object. Then you need to create a new object and call load on it. Also, you should recycle the Primary View before destroying your existing object.

      func refreshInMobiStrandAd() {
              self.tableData.removeAtIndex(self.tableData.indexOf(self.InMobiNativeAd)!)
              self.tableView.reloadData()
              self.InMobiNativeAd.recyclePrimaryView()
              self.InMobiNativeAd = IMNative(placementId: <Insert InMobi placement ID 
                                    here>);
              self.InMobiNativeAd.delegate = self
              self.InMobiNativeAd.load()
      }
      		
    9. Handling Orientation Change - You will need to calculate the new width for Ad Primary View on orientation change and call the [self.InMobiNativeAd primaryViewOfWidth:<custom width>] method again to replace the current Ad Primary View with the new view.
    10. You should set the InMobiNativeAd object and its delegate to nil in the dealloc method of your ViewController class. Do ensure you recycle the view before deallocating to remove all references to the adView.
      deinit {
             self.InMobiNativeAd.recyclePrimaryView()
             self.InMobiNativeAd.delegate = nil
             self.InMobiNativeAd = nil
       }
      		

    Splash Ad Integration

    1. Splash experience can be implemented using the same IMNative Class.
    2. You should use self.InMobiNativeAd.isReady function to determine if the ad is ready to be shown. Sometimes, your main thread may be occupied and hence you may not receive nativeDidFinishLoading in time. Hence, it is better to proactively check if the ad is ready just after your cut-off time has elapsed.
    3. IMPORTANT: You should NOT dismiss the ad if the second screen of the ad is in display. You can check this in the nativeWillPresentScreen and not dismiss the ad if this delegate is fired. Sample implementation is as follows:
      var isSecondScreenDisplayed; // Use this to check if second screen has to be shown or not
      func nativeWillPresentScreen(native: IMNative) {
          NSLog("Native Ad will present screen");
          isSecondScreenDisplayed = true
      }
      		
    4. You should recycle the Primary View before dismissing the ad. This can be implemented as follows:
      var SplashAdView:UIView // Use this to check visibility of second screen
      func dismissAd() {
           if isSecondScreenDisplayed {
                NSLog(“DO NOT DISMISS THE AD WHILE THE SCREEN IS BEING DISPLAYED”)
           }
           else {
                self.SplashAdView.hidden = true
                self.InMobiNativeAd.recyclePrimaryView()
                self.InMobiNativeAd = nil
            }
      }
      		

    Pre-Roll Ad Integration

    1. Pre-Roll Video experience can be implemented using the same IMNative Class. You will need to dismiss the ad view in the following delegate:
      func nativeDidFinishPlayingMedia(native: IMNative) {
              self.dismissAd()
      }
      		
    2. The Pre-Roll ad can be dismissed as follows:
      var PrerollAdView:UIView // Use this to store the primaryView returned by the IMNative instance.
      func dismissAd() {
          self.PrerollAdView.hidden = true
          self.InMobiNativeAd.recyclePrimaryView()
          self.InMobiNativeAd = nil
      }
      		

    Advanced

    You can perform the following steps to get additional callbacks. Implement the following delegate methods in your ViewController.m file:

    func nativeDidFinishLoading(native: IMNative) {
            NSLog("Native Ad load Successful")
            // Ad is ready to be displayed
        }
        func native(native: IMNative, didFailToLoadWithError error: IMRequestStatus) {
            NSLog("Native Ad load Failed")
            // No Fill or error
        }
        func nativeWillPresentScreen(native: IMNative) {
            NSLog("Native Ad will present screen")
            //Full Screen experience is about to be presented
        }
        func nativeDidPresentScreen(native: IMNative) {
            NSLog("Native Ad did present screen")
            //Full Screen experience has been presented
        }
        func nativeWillDismissScreen(native: IMNative) {
            NSLog("Native Ad will dismiss screen")
            //Full Screen experience is going to be dismissed
        }
        func nativeDidDismissScreen(native: IMNative) {
            NSLog("Native Ad did dismiss screen")
            //Full Screen experience has been dismissed
        }
        func userWillLeaveApplicationFromNative(native: IMNative) {
            NSLog("User leave")
            //User is about to leave the app on clicking the ad
        }
        func native(native: IMNative, didInteractWithParams params: [NSObject : 
          AnyObject]) {
            NSLog("User clicked")
            // Called when the user clicks on the ad.
        }
        func nativeAdImpressed(native: IMNative) {
            NSLog("User viewed the ad")
            // Called when impression event is fired.
        }
        func nativeDidFinishPlayingMedia(native: IMNative) {
            NSLog("The Video has finished playing")
            // Called when the video has finished playing. Used for preroll use-case
        }
        func userDidSkipPlayingMediaFrom(native: IMNative) {
            NSLog("User has skipped playing the media")
            // Called when the user has opted to skip the media being shown. 
        }
        Func native(native: IMNative, adAudioStateChanged audioStateMuted: Bool) {
           if (audioStateMuted) {
             NSLog(“Inline state changed to mute”)
           }
           else {
             NSLog(“Inline state changed to unmute”)
           }
        }
    	

    Implementing Backfill

    InMobi's SDK can run both HTML and native units against your native placement. You can run the following ad sizes depending on the real-estate reserved for your native placement.

    • 320x50 HTML Banner
    • 300x250 HTML Banner
    • 320x480 HTML Full screen Banner
    • 320x568 HTML Full screen Banner
    To switch this on, you need to reach out to your respective partner manager with the preferred backfill size. Also, you will need to handle this in your code as follows:
    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    	InFeedTableCell *cell = (InFeedTableCell *)[tableView 
                           dequeueReusableCellWithIdentifier:@"InFeedTableCell"];
    	NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"InFeedTableCell" 
                            owner:self options:nil];
    	cell = [nib objectAtIndex:0];
    	id slide = [self.tableData objectAtIndex:indexPath.row];
    	if ([self isAdAtIndexPath:indexPath]) {
    		IMNative *currentNativeAd = slide;
            	NSString *customJSONstring = currentNativeAd.customAdContent;
           		NSData *data = [customJSONstring dataUsingEncoding:NSUTF8StringEncoding];
            	NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
            	BOOL isBackFillBanner = [[jsonDict objectForKey:@"isHTMLResponse"] boolValue];
    		if (isBackFillBanner) {
    		 {
    			IMNative * currentNativeAd = slide;
    			//Depending on the selected backfill size, provide accurate width below
    			UIView* AdPrimaryViewOfCorrectWidth = [currentNativeAd primaryViewOfWidth:250];
    			AdPrimaryViewOfCorrectWidth.frame = CGRectMake((_screenWidth-300)/2, 0, 300, 250);
               		[cell addSubview:AdPrimaryViewOfCorrectWidth];
    		}
    		else
    		{
    			//continue with the current native implementation
            		IMNative * currentNativeAd = slide;
            		cell.iconImageView.image = currentNativeAd.adIcon;
           			cell.titleLabel.text = currentNativeAd.adTitle;
            		cell.subTitleLabel.text = @"Sponsored";
           			cell.descriptionLabel.text = currentNativeAd.adDescription;
            		cell.ctaLabel.text = currentNativeAd.adCtaText;
    			//Calculate your feed's primaryImageViewWidth and use it to fetch and Ad Primary view of same width.
            		UIView* AdPrimaryViewOfCorrectWidth = [currentNativeAd primaryViewOfWidth:primaryImageViewWidth];
    			//Set the frame of Ad Primary View same as that of your feed's Primary View
    			AdPrimaryViewOfCorrectWidth.frame = primaryImageViewFrame;
               		 [cell addSubview:AdPrimaryViewOfCorrectWidth];
               		 UITapGestureRecognizer *singleTapAndOpenLandingPage = 
                  		[[UITapGestureRecognizer alloc] initWithTarget:currentNativeAd 
                  		action:@selector(reportAdClickAndOpenLandingPage)];
            		cell.ctaLabel.userInteractionEnabled = YES;
            		[cell.ctaLabel addGestureRecognizer:singleTapAndOpenLandingPage];
        		}
    	}	
    	else {
    		//Your App’s TableCell implementation
    	}
            return cell;
    }
    	

    Note:

    • To detect if the response is backfill, the customAdContent will contain the string isHTMLResponse.
    • Do NOT scale the width of the HTML banner response. For e.g. if you selected backfill of 300x250, make sure the provided width is hardcoded 250.
    • Do NOT add the CTA button in case of backfill response. The clicks will not be monetized in case you add this button alongside the ad.

    Retrieving CreativeID

    At times, there are rogue advertisers who escape all the ad quality checks and end up compromising the user experience on the app by showcasing either an irrelevant, distasteful or disrupting creative to the user. To combat such situations, you can retrieve the creativeID of the ad instance and report back to your InMobi point of contact with the encrypted creativeID. Access the below property after ad load success callback is received.

    @property (nonatomic, strong, readonly) NSString* creativeId;

    Testing the Integration

    1. Configure the Test Mode on InMobi portal.

      Go to Tools - Diagnostics and switch Test Mode to either Global ON or Selective ON.

      If you are integrating an ad unit for the first time Set Test Mode to Global ON.
      If you want to selectively turn on test traffic for a set of devices·

      You already have a prior version of the SDK integrated for this particular ad unit and therefore you should restrict your testing to only few devices
      Set Test Mode to Selective ON.

      In the device section:

      1. In the Device ID box, type the device ID.
      2. In the Device Name box, set any name.
      3. Click Add Device to add the test device.

      If you already have a device configured, you can select the device and test mode will be enabled.

      Note: You MUST turn off the test mode before going live or else your app will fail to monetize.

      Now you are all set to get test ads.

      Getting the Device ID

      import AdSupport
      let deviceId = ASIdentifierManager.shared().advertisingIdentifier.uuidString
      		

      You can enter this device id in the Device ID box.

    2. You will also get feedback on the diagnostics tab on the ad unit and ad request and this can be particularly helpful during integration.

    3. You should also see these key InMobi SDK logs in console when a native ad is successfully loaded:

      [InMobi] InMobi SDK initialized with account id: <your account id here>

      [InMobi] Fetching native ad for placement id: <your placement id here>

      [InMobi] Publisher device id is <device id here>

      [InMobi] Native ad successfully fetched for placement id: <your placement id here>

    4. Now you would also see the InMobi test ads on your application.
    5. If the SDK is not initialised correctly before creating an ad, you would typically see these logs :

      ** ERROR ** [InMobi] ___ Please initialize the SDK before creating a <ad format> ad.

      ** ERROR ** [InMobi] ___ Account id cannot be null or empty. Please provide a valid Account id.

      [InMobi] Invalid account id passed to init. Please provide a valid account id.

    Common SDK Initialization Messages

    Log Level Scenario Displayed Message
    Error SDK is not initialized Please initialize the SDK before creating xxx ad.
    Error The ATS state for Ad server URL is invalid ATS Configuration not supported. Kindly remove InMobi from the exception list.
    Error Account ID provided to initializeSDKWithAccountID is empty or null. Account id cannot be null or empty. Please provide a valid Account id.
    Debug Publisher passed a valid account id InMobi SDK initialized with account id:<Account-Id>
    Debug When account id length is not valid Invalid account id passed to init. Please provide a valid account id.
    Debug Newer version of SDK is available A newer version (ver. 9.0.0) of the InMobi SDK is available! You are currently on an older version (Ver. 6.0.0). Please download the latest InMobi SDK from http://www.inmobi.com/products/sdk/#downloads

    Common Ad Lifecycle Messages

    Log Level Scenario Displayed Message
    Error PlacementID provided is invalid (<=0) Please provide a valid placement id to create a xx ad.
    Error Invalid banner placement id is being called Please give a valid placement id before calling load
    Error Current state of ad is Loading or AdAvailable An ad load is already in progress. Please wait for the load to complete before requesting for another ad. Rejected placement id: xx
    Error Current state of ad is Active An ad is currently being viewed by the user. Please wait for the user to close the ad before requesting for another ad. Rejected placement id: xx
    Error Ad is being refreshed before the minimum refresh interval as mentioned in config Ad cannot be refreshed before xxx secs
    Error Current state of ad is not ready. Ad Load is not complete. Please wait for the Ad to be in a ready state before calling show
    Error Show is called on an Interstitial ad, but the app does not currently pass a view controller Full screen ad cannot be displayed without a view controller. Please pass a view controller to present the full screen ad.
    Error Current state of ad is not attached/ rendered or active. reportAdClick call made in wrong state
    Debug When Monetization is disabled from config SDK will not perform this load operation as monetization has been disabled. Please contact InMobi for further info.

    exchange | Android Native test

    InMobi Native ads seamlessly blend in with your app’s content, maximizing user engagement without compromising on user experience. You can choose and customize the layout that best matches the design of your app. It is ideal for news, utility and communication apps.

    InMobi Native Ads can have video and/or static image both. Depending on the placement you can opt for:

    • In-Feed Ad - a muted autoplay HD video or a simple static image ad.
    • Splash Ad - blends in the launch screen of apps and monetize user time when the app is loading in the background. These ads can also be a muted autoplay HD video ad or a simple static image ad.

    Static Feed Ad

    InFeed Video Ad

    Splash Video Ad

    Follow these simple steps and start monetizing with Native ads:

    Setting up a Native Ad Placement

    1. Create a Native Content placement.

    2. In-Feed Video Ad Placement
      1. Select FEED as the Native Ad Layout.

      2. For In-Feed Video, select either of the aspect ratio 256:135 or 16:9. Both the aspect ratios will have default static native fallback enabled with similar aspect ratio.

    3. Static Feed Ad Placement
      1. Select FEED as the Native Ad Layout.

      2. In the integration code, please ensure nativeAd.getPrimaryViewOfWidth(context,convertView, parent, width);Specify width = 25 while fetching your primaryView. It will just show the AdChoices icon and fire the ad render events.
    4. Splash Video Ad Placement
      • Select SPLASH as the Native Ad Layout.

      • Select the desired aspect ratio. Default value for the aspect ratio will be 9:16.

    5. Others (China only):
      • Select Others as the Native Ad Layout.

      • Select aspect ratio 16:9. This will have default static native fallback enabled with similar aspect ratio.
      • A new sub field is added in Others layout called Native Layout Type. It has the following values: “Native Interstitial”, “Native Page”, “Native Banner”, “Native Focus”, “Native Lock Screen”, “Native Other”.
      • Default value will be Native Interstitial in Native layout type field.

      • Save the Pre-roll native placement layout.

    Adding a Native Ad to Your App

    Creating a Native Ad

    To create a native ad, create an InMobiNative instance:

    public class NativeAdsActivity extends Activity {
    ……………………
    private final List<InMobiNative> mNativeAds = new ArrayList<>();
    ……………………
    InMobiNative nativeAd = new InMobiNative(NativeAdsActivity.this, YOUR_PLACEMENT_ID, nativeAdEventListener);
    nativeAd.load();
    mNativeAds.add(nativeAd);
    ……………………
    	

    Here nativeAdEventListener is an implementation of the NativeAdEventListener abstract class. It is mandatory to supply an implementation of this interface to create a native ad.

    Mandatory: You must supply a Context implementation to the InMobiNative constructor. Please make sure your implementation holds a strong reference of InMobiNative otherwise you will not be able to get any callback from SDK for this reference. This can be achieved by making it a member variable of a class or storing it in collection, which lives through your application life cycle.

    • inMobiNative should always be strong reference otherwise you may not receive any callback (load success, load failure etc.) for this reference.
    • If inMobiNative is referenced by any variable please ensure that it is a strong reference.
    • Use android profiler to ensure that inMobiNative is not removed due to garbage collection.

    NativeAdEventListener abstract class allows you to listen to key lifecycle events for a native ad.

    /**
    * A listener for receiving notifications during the lifecycle of a Native ad.
    */
    public abstract class NativeAdEventListener {
    /**
    * Called to indicate that an ad is available in response to a request for an ad (by calling
    * {@link InMobiNative#load()}. <p class="note"><strong>Note</strong> This does not
    * indicate that the ad can be shown yet. Your code should show an ad <strong>after</strong> the
    * {@link #onAdLoadSucceeded(InMobiNative)} method is called. Alternately, if you do not
    * want to handle this event, you must test if the ad is ready to be shown by checking the
    * result of calling the {@link InMobiNative#isReady()} method.</p>
    *
    * @param ad Represents the {@link InMobiNative} ad for which ad content was received
    */
    public void onAdReceived(InMobiNative ad) {}
    /**
    * Called to indicate that an ad was loaded and it can now be shown. This will always be called
    * <strong>after</strong> the {@link #onAdReceived(InMobiNative)} callback.
    *
    * @param ad Represents the {@link InMobiNative} ad which was loaded
    */
       public void onAdLoadSucceeded(InMobiNative ad) {}
       /**
        * Called to notify that a native ad failed to load.
        *
        * @param ad  Represents the {@link InMobiNative} ad which failed to load
        * @param requestStatus Represents the {@link InMobiAdRequestStatus} status containing error reason
        */
       public void onAdLoadFailed(InMobiNative ad, InMobiAdRequestStatus requestStatus) {}
       /**
        *
        * @param ad  Represents the {@link InMobiNative} ad whose fullscreen was dismissed
        */
       public void onAdFullScreenDismissed(InMobiNative ad) {}
       /**
        * Called to notify that the ad will open an overlay that covers the screen.
        *
        * @param ad Represents the {@link InMobiNative} ad which will go fullscreen
        */
       public void onAdFullScreenWillDisplay(InMobiNative ad) {}
       /**
        * Called to notify that the ad opened an overlay that covers the screen.
        *
        * @param ad Represents the {@link InMobiNative} ad whose fullscreen will be displayed
        */
       public void onAdFullScreenDisplayed(InMobiNative ad) {}
       /**
        * Called to notify that the user is about to leave the application as a result of interacting with it.
        *
        * @param ad Represents the {@link InMobiNative} ad
        */
       public void onUserWillLeaveApplication(InMobiNative ad) {}
       /**
        * Called to notify impression has been recorded for this ad. <b>Note:</b>Override this method to notify
        * viewable impression to the Mediation Adapter.
        *
        * @param ad Represents the {@link InMobiNative} ad for which impression is recorded.
        */
       public void onAdImpressed(InMobiNative ad) {}
       /**
        * Called to notify ad was clicked. <b>Note:</b>Override this method to notify click to the Mediation Adapter.
        *
        * @param ad Represents the {@link InMobiNative} ad which was clicked
        */
       public void onAdClicked(InMobiNative ad) {}
       /**
        * Called to notify that the ad status has changed.
        *
        * @param nativeAd Represents the {@link InMobiNative} ad
        */
       public void onAdStatusChanged(InMobiNative nativeAd) {}
    }
    	

    VideoEventListener abstract class allows you to listen to video lifecycle events for a native ad.

    /**
    * A listener for receiving notifications during the lifecycle of a Native ad.
    */
    public abstract class VideoEventListener {
       /**
        * Called to notify that the video has finished playing.
        *
        * @param ad Represents the {@link InMobiNative} ad
        */
       public void onVideoCompleted(InMobiNative ad) {
       }
       /**
        * Called to notify that the user has skipped video play.
        *
        * @param ad Represents the {@link InMobiNative} ad
        */
       public void onVideoSkipped(InMobiNative ad) {
       }
       /**
        * Called to notify when media audio state changes.
        *
        * @param isMuted Represents whether media is muted or not.
        */
       public void onAudioStateChanged(InMobiNative inMobiNative, boolean isMuted) {
       }
    }
    	


    Loading a Native Ad

    To request for a native ad, call the load() method on the InMobiNative instance you created above:

    nativeAd.load();
    	

    The NativeAdEventListener abstract class notifies the result of this method. If the ad request was successful, the onAdReceived(InMobiNative) event is generated. This is followed by either the onAdLoadSucceeded or the onAdLoadFailed event. If the onAdLoadFailed event is generated, the reason is indicated by the InMobiAdRequestStatus object passed in this event.


    Listening to video events

    To receive video events register videoEventListener using method setVideoEventListener (VideoEventListener videoEventListener) on the InMobiNative instance you created above:

    nativeAd.setVideoEventListener (videoEventListener);
    	

    The VideoEventListener abstract class notifies you about video events for native ads.


    Native Ad APIs

    Following are the important APIs in InMobiNative that will help to stitch the ads:

    • View getPrimaryViewOfWidth(context, convertView, parent, width) - Returns a View of specified width (specified in actual pixels). This is the main ad content in your native ad. It will return a view of the same aspect ratio that you selected on the InMobi dashboard while creating the native placement. All impression render events are also fired automatically when this primary view is displayed on the screen.

      If you have selected Feed Layout while creating your placement, specify width = 25 while fetching your primaryView. It will just show the AdChoices icon and fire the ad render events.

      getPrimaryViewOfWidth(..) takes in four parameters:

      • context - The context in which ad is going to be rendered.
      • convertView - This is the complete view of a row of the ListView. You should not provide this as NULL because we use this parameter to recycle our ads effectively. This will allow for a smooth scroll performance.
      • parentView - This is the parent view inside which you will place the primaryView (which is returned by getPrimaryViewOfWidth() function). We need it for determining the layout parameters of Primary View.
      • adViewWidthInPixels - This is the width (in pixels) that you want the primaryView to take up.
    • String getAdTitle() - returns the string title for the ad.
    • String getAdDescription() - returns the string description for the ad.
    • String getAdIconUrl() - returns icon Image String URL for the ad.
    • String getAdCtaText() - returns Click to action string for the ad.
    • String getAdRating() - returns rating for the ad (optional).
    • String getAdLandingPageUrl() - returns landing URL for the ad.
    • boolean isAppDownload - returns true when the featured ad is from an app install advertiser.
    • boolean isReady() - True means the ad is ready to be displayed.
    • Boolean isVideo() - returns a Boolean if the ad returned contains a video or not, returns null if it is called in a wrong state.
    • void reportAdClickAndOpenLandingPage() - This function fires the click events and opens the landing page. You need not open landing page on your own while using this function.
    • JSONObject getCustomAdContent() - This function returns the JSONObject. This json have additional information (description, image URL, etc.), which can be used to create custom UI around the primary view of the ad.


    Stitching a Native Ad

    A native ad can be stitched in your app in three formats:

    • In-Feed ads
    • Splash ads
    • Pre-Roll ads

    InFeed Ad Integration
    1. Declare an ad position in your feed where you want to show ad.

      For example, to show ad at 4th position:

      private static final int AD_POSITION = 4;
      		
    2. If the ad load is successful, you will get a callback onAdLoadSucceeded(InMobiNative).You should then add the InMobiNativeAd object to your data source within this listener. If your feed in the app is a ListView, a sample implementation for ListView is shown below:
      @Override
             public void onAdLoadSucceeded(@NonNull InMobiNative nativeAd) {
      		AdFeedItem nativeAdFeedItem = new AdFeedItem(nativeAd);
      		mFeedItems.add(AD_POSITION, nativeAdFeedItem);
      		mFeedAdapter.notifyDataSetChanged();
             }
      		

      In the step above, AdFeedItem is an extension class of your FeedItem class, where FeedItem is the class which powers each row of your ListView. Also mItems is the ArrayList, which powers the Adapter of this ListView.

    3. So far, we have loaded an ad and added it to your data source. Now, it’s time to display the ad. The sample implementation for ListView is as follows:
      @Override
      public View getView(int position, View convertView, ViewGroup parent) {
         final int itemViewType = getItemViewType(position);
         if (itemViewType == VIEW_TYPE_CONTENT_FEED) {
      		//Your app code
         } else {
      	//Since this content type is InMobi Ad, you need to get native Ad view		
             final InMobiNative nativeAd = ((AdFeedItem) feedItem).mNativeAd;
      	View primaryView = nativeAd.getPrimaryViewOfWidth(context, convertView, parent, parent.getWidth());
      		       if(convertView==null){
                convertView = mLayoutInflater.inflate(R.layout.ad_item, parent, false);
             }
                              ((RelativeLayout)convertView.findViewById(R.id.primaryView)).addView(primaryView);
            ((TextView)convertView.findViewById(R.id.title)).setText(nativeAd.getTitle());
            ((TextView)convertView.findViewById(R.id.desc)).setText(nativeAd.getDescription());
            ((TextView)convertView.findViewById(R.id.cta)).setText(nativeAd.getCtaText());
             return convertView;
         }
      }
      		

      The function getItemViewType(position) checks whether the content type is FEED OR AD as given below:

      @Override
      public int getItemViewType(int position) {
         FeedItem feedItem = getItem(position);
         if (feedItem instanceof AdFeedItem) {
             return VIEW_TYPE_INMOBI_STRAND;
         }
         return VIEW_TYPE_CONTENT_FEED;
      }
      		

      We have used some of the APIs described in the section above to show the title, description, and CTA text of the ad. Similarly, the other APIs can be used to show the corresponding parts of the ad.


    Splash Integration

    Splash experience can be implemented using the same InMobiNative class. However, there are a few things to be noted:

    • You should use InMobiNativeAd.isReady() function to determine if the ad is ready to be shown. Sometimes, your main thread may be occupied and hence you may not receive onAdLoadSucceeded in time. Hence, it is better to proactively check if the ad is ready just after your cut-off time has elapsed.
    • IMPORTANT: You should NOT destroy or refresh the ad if the second screen of the ad is in display. You can check this in the onAdFullScreenDisplayed and not dismiss the ad if this callback is fired.

    Sample implementation is as follows:

    @Override
    public void onAdFullScreenDisplayed(InMobiNative nativeAd) {
    	isSecondScreenDisplayed = YES;
    }
    public void dismissAd() {
       if(isSecondScreenDisplayed){
           Log.d(TAG, "DO NOT DISMISS THE AD WHILE THE SCREEN IS BEING DISPLAYED");
       }
       else
       {
    	splashAdView.setVisibility(View.GONE);
    	nativeAd.destroy();
       }
    }
    	

    Pre-Roll Integration

    Pre-Roll Video experience can be implemented using the same InMobiNative Class. You need to register videoEventListener and need to dismiss the ad view in the following callback:

    @Override
    public void onVideoCompleted(@NonNull InMobiNative nativeAd) {
    	Log.d(TAG, "Media playback complete " + mPosition);
    }
    	

    The Pre-Roll ad can be dismissed as follows:

    public void dismissAd() {
    	splashAdView.setVisibility(View.GONE);
    	nativeAd.destroy();
    }
    	

    Refreshing the Native Ad

    You will need to refresh the ad at various points to optimize ad exposure to your users. To refresh the ad, you will need to call the following functions in the exact order.

    Note: It is important to remove the adFeedItem object from your data source and destroying it before refreshing. You will then need to create a new object and call load as shown in the following code:

    private void refreshAd() {
           Iterator<FeedItems> feedItemIterator = mFeedItems.iterator();
           while (feedItemIterator.hasNext()) {
               final FeedItem feedItem = feedItemIterator.next();
               if (feedItem instanceof AdFeedItem) {
                   feedItemIterator.remove();
               }
           }
           // refresh feed
           mFeedAdapter.notifyDataSetChanged();
           // destroy InMobiNative object
           inMobiNativeAd.destroy();
           // create InMobiNative object again
    	InMobiNative inMobiNativeAd = new InMobiNative(
    	<<Activity Instance>>,
    	<<Your Placement ID>>,
    	<<InMobiNativeAdListener created in step 1>>);
    	inMobiNativeAd.load();
    }
    	

    Managing the InMobiNative Instances

    1. Every instance of InMobiNative represents exactly one ad.
    2. If you want to place ad at multiple positions within a content feed, create as many instances of InMobiNative as the number of ad positions.
    3. You should create instances of InMobiNative in onCreate() callback of Activity or in onActivityCreated() callback of Fragment.
    4. You should destroy the InMobiNative instances in onDestroy() callback of Activity or in OnDestroyView() callback of Fragment.
    5. An InMobiNativeAd object must always be destroyed once you remove it from the data source. All user interactions with the ad view will not be honored after InMobiNativeAd is destroyed. So, you will have to definitely discard the ad view before destroying the InMobiNativeAd.
    6. All InMobiNativeAd instances must also be destroyed, when the component hosting them (your activity in this case) is getting destroyed using the destroy() API.

    Click Tracking on the Ad Views

    To have the InMobi SDK open the landing URL in addition to reporting a click, call the reportAdClickAndOpenLandingPage() method on the native ad instance:

    nativeAd.reportAdClickAndOpenLandingPage();
    	

    Downloader Integration (If you want to monetize China traffic)

    Introduction

    In China, due to absence of Google Play, we support direct downloading of APKs through a tool called InMobi Downloader. This feature is available only in the China version of InMobi Android SDK. The InMobi Downloader manages the advertiser app download and installation. It communicates events to the advertisers to enable attribution while providing a bespoke experience for publishers and users.

    Changing the Manifest File

    You need to add a new service to manifest file as follows:

    <service
    	android:name="com.inmobi.ads.ApkDownloader$ApkDownloadService"
    	android:enabled="true">
    </service>
    	

    The downloader requires the permission to write external storage as follows:

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    	

    Android 7 (Nougat and above)

    New changes are required from Android N onwards, since the design for file sharing has changed. Other applications cannot access the files of your app, and hence we will need the PackageInstaller app to install the APK file downloaded by us. Reference here.

    • Add res/xml/provider.xml
      <?xml version="1.0" encoding="utf-8"?>
      <paths xmlns:android="http://schemas.android.com/apk/res/android">
         <external-path name="external_files" path="."/>
      </paths>
      		
    • In AndroidManifest.xml, add the following:
      <provider
         android:name="android.support.v4.content.FileProvider"
         android:authorities="{appPackageName}.fileprovider"
         android:exported="false"
         android:grantUriPermissions="true">
         <meta-data
             android:name="android.support.FILE_PROVIDER_PATHS"
             android:resource="@xml/provider" />
      </provider>
      		
    • For Android Oreo (8 and above), add the following in AndroidManifest.xml:
      <uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
      		

    Invoking InMobi Downloader

    You need to enable downloader while creating your InMobi native ad object as follows:

    @Override
    public void onCreate(Bundle savedInstanceState) {
    	super.onCreate(savedInstanceState);
    	InMobiNative nativeAd = new InMobiNative(
    	<<Activity Instance>>,
    	<<Your Placement ID>>,
    	<<InMobiNativeAdListener>>);
    	nativeAd.setDownloaderEnabled(true);
    	nativeAd.load();
    	//Your App code here
    }
    	

    Getting Downloader Callbacks

    The InMobi Downloader provides callbacks in the listener method named onAdStatusChanged(). This will be fired every time the downloader changes its state. The status can be accessed through getDownloadStatus() method. The possible states and their corresponding status messages are:

    STATE_UNINITIALIZED = -2;
    STATE_INITIALIZING = -1;
    STATE_DOWNLOADING = 0;
    STATE_DOWNLOADED = 1;
    STATE_ERROR = 2;
    	

    During the state when the downloader is downloading the APK ( STATE_DOWNLOADING = 0), you can access the progress of download using getDownloadProgress() method. You can use this progress to show a progress bar to your users.

    Note: Do note that onAdStatusChanged() is fired every time the download percentage changes within the state STATE_DOWNLOADING = 0. A sample implementation of this is shown below:

    public void onAdStatusChanged(@NonNull InMobiNative nativeAd) {
    	Log.d("InMobi Downloader status is", "value: " + nativeAd.getDownloader().getDownloadStatus());
    	if (nativeAd.getDownloader().getDownloadStatus() == InMobiNative.Downloader.STATE_DOWNLOADING) {
    	progressBar.setProgress(nativeAd.getDownloader().getDownloadProgress());
    	}  
    }
    	

    Implementing Backfill

    InMobi's SDK can run both HTML and native units against your native placement. You can run the following ad sizes depending on the real-estate reserved for your native placement.

    • 320x50 HTML Banner
    • 300x250 HTML Banner
    • 320x480 HTML Full screen Banner
    • 320x568 HTML Full screen Banner
    To switch this on, you need to reach out to your respective partner manager with the preferred backfill size. Also, you will need to handle this in your code as follows:
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
       final int itemViewType = getItemViewType(position);
       if (itemViewType == VIEW_TYPE_CONTENT_FEED) {
    		//Your app code
     	} 
       else {
       		//Since this content type is InMobi Ad, you need to get native Ad view
    		final InMobiNative nativeAd = ((AdFeedItem) feedItem).mNativeAd;
    		//Detect whether its a backfill response or normal native
    		JSONObject customContent = currentNativeAd.getCustomAdContent();
                    boolean isBackFillBanner = false;
                    try {
                        isBackFillBanner = customContent.getBoolean("isHTMLResponse");
                    } catch (JSONException e) {
                        isBackFillBanner = false;
                    }
    		if(isBackFillBanner){	
    			View primaryView = nativeAd.getPrimaryViewOfWidth(context, convertView, parent, Math.round(getResources().getDisplayMetrics().density*250));
     		   	if(convertView==null){
     	         		convertView = mLayoutInflater.inflate(R.layout.ad_item, parent, false);
     	       		}
    			((RelativeLayout)convertView.findViewById(R.id.primaryView)).addView(primaryView);
    			return convertView;
    		} 
    		else {
    		 	View primaryView = nativeAd.getPrimaryViewOfWidth(context, convertView, parent, parent.getWidth());
    		   	if(convertView==null){
    	         		 convertView = mLayoutInflater.inflate(R.layout.ad_item, parent, false);
    	       		}
    		  	((RelativeLayout)convertView.findViewById(R.id.primaryView)).addView(primaryView);
    		   	((TextView)convertView.findViewById(R.id.title)).setText(nativeAd.getTitle());
    		   	((TextView)convertView.findViewById(R.id.desc)).setText(nativeAd.getDescription());
    		   	((TextView)convertView.findViewById(R.id.cta)).setText(nativeAd.getCtaText());
    		  	 return convertView;
       		}
    	}
    }
    	

    Note:

    • To detect if the response is backfill, the customAdContent will contain the string isHTMLResponse.
    • Do NOT scale the width of the HTML banner response. For e.g. if you selected backfill of 300x250, make sure the provided width is hardcoded 250.
    • Do NOT add the CTA button in case of backfill response. The clicks will not be monetized in case you add this button alongside the ad.

    Retrieving CreativeID

    At times, there are rogue advertisers who escape all the ad quality checks and end up compromising the user experience on the app by showcasing either an irrelevant, distasteful or disrupting creative to the user. To combat such situations, you can retrieve the creativeID of the ad instance and report back to your InMobi point of contact with the encrypted creativeID.

    mNativeAd.getCreativeId()// mNativeAd is an example instance.

    Testing the Integration

    1. Configure the test mode on InMobi portal.

      Go to Tools - Diagnostics and switch Test Mode to either Global ON or Selective ON.

      If you are integrating an ad unit for the first time Set Test Mode to Global ON.
      If you want to selectively turn on test traffic for a set of devices·

      You already have a prior version of the SDK integrated for this particular ad unit and therefore you should restrict your testing to only few devices
      Set Test Mode to Selective ON.

      In the device section:

      1. In the Device ID box, type the device ID.
      2. In the Device Name box, set any name.
      3. Click Add Device to add the test device.

      If you already have a device configured, you can select the device and test mode will be enabled.

      Note: You MUST turn off the test mode before going live or else your app will fail to monetize.

      Now you are all set to get test ads.

      Getting the Device ID

      The device id is the Google Play Advertising ID (GPID). To get the device ID, configure the SDK to print debug logs to the console. You can do so by adding the following line to your Activity where you are integrating Native ads.

         InMobiSdk.setLogLevel(LogLevel.DEBUG);
      		

      The device ID will now be printed in debug logs in the DDMS console like so:

    2. You will also get feedback on the diagnostics tab on the ad unit and ad request and this can be particularly helpful during integration.

    Helpful Debug Information

    Once you have enabled debug logs as mentioned in step 1, SDK will print key logs to the DDMS console that provide useful information about the initialization and ad load lifecycle.

    The following table captures these logs.

    SDK Initialization
    Scenario Log Level Log Message
    Publisher passed null or empty account id Error Account id cannot be null or empty. Please provide a valid Account id.
    Publisher passed a valid account id Debug InMobi SDK initialized with account id: <account id>
    Publisher passed an invalid account Id Error Invalid account id passed to init. Please provide a valid account id.
    Publisher didn't grant the mandatory permissions Debug Please grant the mandatory permissions : INTERNET & ACCESS_NETWORK_STATE, SDK could not be initialized.
    Permissions granted to the SDK Debug Permissions granted to the SDK are : <List of permissions granted>
    Newer version of SDK is available Debug A newer version (ver. 9.0.0) of the InMobi SDK is available! You are currently on an older version (ver. 5.3.1). Download the latest InMobi SDK from http://www.inmobi.com/products/sdk/#downloads

    Common Ad Lifecycle Messages
    Scenario Log Level Log Message
    Ad requested when no network available Error Network not reachable currently. Please try again.
    Ad requested when ad state is loading or available Error An ad load is already in progress. Please wait for the load to complete before requesting for another ad (Placement id : <placement id> ).
    Publisher device Id Debug Publisher device id is <Device Id>

    Messages for Native Ad Integrations
    Scenario Log Level Log Message
    Publisher supplied a null context Error Unable to create InMobiNative ad with null Activity object
    Publisher created a native ad without initializing the SDK Error Please initialize the SDK before creating a Native ad
    Publisher created a native ad with an invalid placement id Error NA
    Publisher supplies a null InMobiNativeAdListenerobject Error Listener supplied is null,the Native Ad cannot be created
    Publisher called load on a native Debug Fetching a Native ad for placement id: <placement id>
    Ad is successfully fetched from server Debug Native ad successfully fetched for placement id: <placement id>
    Failed to fetch the ad Error Failed to fetch Native ad for placement id : <Placement id> with error : <Status code / message>
    When AdView is inflated Debug Ad markup loaded into the container will be inflated into a View

    Advanced

    Lock Screen Ads

    For lock screen integration, you may want to prefetch ads and not tie them to any specific activity. The InMobi SDK allows you to create native ad units that can be maintained in your Application subclass. Your app can then use the native ad unit in your lock screen Activity where the monetization event will occur.

    • Prefetch native ads: create an InMobiAdRequest to supply specific targeting information to the ad server.
    • Call InMobiNative.requestAd(Context, InMobiAdRequest, NativeAdRequestListener) by supplying an implementation for the NativeAdRequestListener interface as mentioned below:
      public class YourApplication extends Application {
          ... 
          private InMobiAdRequest mInMobiAdRequest;
          private NativeAdRequestListener mListener;
          Private InMobiNative mNativeAd;
          ...
          public void onCreate() {
              mInMobiAdRequest = new InMobiAdRequest.Builder(PlacementId.YOUR_PLACEMENT_ID)
                      .build();
              mListener = new InMobiNative.NativeAdRequestListener() {
                  @Override
                  public void onAdRequestCompleted(InMobiAdRequestStatus status, InMobiNative nativeAd) {
                      if (status.getStatusCode() == NO_ERROR && nativeAd != null) {
                          mNativeAd = nativeAd;
                      } 
                  }
              };
              InMobiNative.requestAd(this, mInMobiAdRequest, mListener);
              ...
          }
          public InMobiNative getNativeAd() {
              return mNativeAd;
          }
      }
      		
    • In your Activity, you can then get an instance of this ad unit by calling the getNativeAd() method on your Application subclass.

      Register this native instance for lockscreen actions using showOnLockScreen(LockScreenListener lockScreenListener). This listener will be invoked as soon as user interacts with ad and lock screen needs to be dismissed to complete this interaction.

      * This method should be called before load(Context) or load().

    • Load the ad markup by calling load(Context), and supply your Activity where the monetization event will occur.
    • Post ad load, request for ad assets by call getAdContent() to fetch assets.

      takeAction()

    • Call this method to take action which is caused by any user interaction with ad view on Lockscreen. This interaction will be reported by com.inmobi.ads.InMobiNative.LockScreenListener#onActionRequired(InMobiNative). This method should be called by app after android.content.Intent.ACTION_USER_PRESENT broadcast.

    exchange | Android reward-test

    Rewarded Video ads are short (15 sec), non-skippable HD videos, which a user opts-in to watch in exchange for rewards like virtual goods or in-game gifts. Preferred by acquisition and brand marketers, these are perfect for integrating in shop fronts, start of gameplay or end of gameplay and help increase the retention of the non paying users. With the reward action dependent only on completed video views, rewarded video ads provide high quality engaged users to advertisers and high eCPMs to publishers.

    Follow these simple steps and start monetizing with Rewarded Video ads:

    Setting up a Rewarded Video Ad

    To display a fullscreen video ad, you’ll need an interstitial placement ID. After adding your app, select REWARDED VIDEO to create a placement for ad type interstitial. The placement ID is available once you successfully create the placement.

    Once you select the placement type as rewarded video, the following appears.

    You can fill in the key value pair for the reward details. The SDK will honour when providing the callback when the user has completed the requisite action. For example, you could fill in the following reward details:
    Key = Coins
    Value = 1000

    Note: InMobi SDK provides you the callback in any case, so you could choose not to fill in anything and handle the rewards completely at your end.

    Adding a rewarded Video Ad to your App

    Creating a Rewarded Video Ad

    To create a rewarded video ad, create an instance of an InMobiInterstitial:

    InMobiInterstitial interstitialAd = new InMobiInterstitial(InterstitialAdsActivity.this, 1471550843414L, mInterstitialAdEventListener);
    	

    Here, mInterstitialAdEventListener is an implementation of the InterstitialAdEventListener abstract class. It is mandatory to supply an implementation of this interface to create an interstitial ad.

    Note: The InMobiInterstitial class is not thread-safe. An interstitial instance must be created on the UI thread. Similarly, all methods on this instance must be called on the UI thread. Not doing so will lead to unpredictable behavior and may affect your ability to monetize with InMobi.

    The InterstitialAdEventListener abstract class allows you to listen to key lifecycle events for an interstitial ad. You should listen to these events to ensure that your application correctly handles the various lifecycle transitions.

       /**
    * Listener for receiving notifications during the lifecycle of an interstitial.
    */
    public abstract class InterstitialAdEventListener {
       /**
        * Called to indicate that an ad was loaded and it can now be shown. This will always be called
        * <strong>after</strong> the {@link #onAdReceived(InMobiInterstitial)} callback.
        *
        * @param ad Represents the {@link InMobiInterstitial} ad which was loaded
        */
       public void onAdLoadSucceeded(InMobiInterstitial ad) {}
       /**
        * Callback to signal that a request to fetch an ad (by calling
        * {@link InMobiInterstitial#load()} failed. The status code indicating the reason for failure
        * is available as a parameter. You should call {@link InMobiInterstitial#load()} again to
        * request a fresh ad.
        *
        * @param ad Represents the {@link InMobiInterstitial} ad which failed to load
        * @param status Represents the {@link InMobiAdRequestStatus} status containing error reason
        */
       public void onAdLoadFailed(InMobiInterstitial ad, InMobiAdRequestStatus status) {}
       /**
        * Called to indicate that an ad is available in response to a request for an ad (by calling
        * {@link InMobiInterstitial#load()}. <p class="note"><strong>Note</strong> This does not
        * indicate that the ad can be shown yet. Your code should show an ad <strong>after</strong> the
        * {@link #onAdLoadSucceeded(InMobiInterstitial)} method is called. Alternately, if you do not
        * want to handle this event, you must test if the ad is ready to be shown by checking the
        * result of calling the {@link InMobiInterstitial#isReady()} method.</p>
        *
        * @param ad Represents the {@link InMobiInterstitial} ad for which ad content was received
        */
       public void onAdReceived(InMobiInterstitial ad) {}
       /**
        * Called to indicate that an ad interaction was observed.
        *
        * @param ad Represents the {@link InMobiInterstitial} ad on which user clicked
        * @param params Represents the click parameters
        */
       public void onAdClicked(InMobiInterstitial ad, Map<Object, Object> params) {}
       /**
        * Called to indicate that the ad will be launching a fullscreen overlay.
        *
        * @param ad Represents the {@link InMobiInterstitial} ad which will display
        */
       public void onAdWillDisplay(InMobiInterstitial ad) {}
       /**
        * Called to indicate that the fullscreen overlay is now the topmost screen.
        *
        * @param ad Represents the {@link InMobiInterstitial} ad which is displayed
        */
       public void onAdDisplayed(InMobiInterstitial ad) {}
       /**
        * Called to indicate that a request to show an ad (by calling {@link InMobiInterstitial#show()}
        * failed. You should call {@link InMobiInterstitial#load()} to request for a fresh ad.
        *
        * @param ad Represents the {@link InMobiInterstitial} ad which failed to show
        */
       public void onAdDisplayFailed(InMobiInterstitial ad) {}
       /**
        * Called to indicate that the fullscreen overlay opened by the ad was closed.
        *
        * @param ad Represents the {@link InMobiInterstitial} ad which was dismissed
        */
       public void onAdDismissed(InMobiInterstitial ad) {}
       /**
        * Called to indicate that the user may leave the application on account of interacting with the ad.
        *
        * @param ad Represents the {@link InMobiInterstitial} ad
        */
       public void onUserLeftApplication(InMobiInterstitial ad) {}
       /**
        * Called to indicate that rewards have been unlocked.
        *
        * @param ad Represents the {@link InMobiInterstitial} ad for which rewards was unlocked
        * @param rewards Represents the rewards unlocked
        */
       public void onRewardsUnlocked(InMobiInterstitial ad, Map<Object, Object> rewards) {}
     }

    Loading a Rewarded Ad

    To request for a interstitial ad, call the load() method on the InMobiInterstitial instance:

    interstitialAd.load();

    You will be notified of the result of this method via the InterstitialAdListener2 event interface. If the ad request was successful, the onAdReceived(InMobiInterstitial) event will be generated. This will be followed by either the onAdLoadSucceeded or the onAdLoadFailed event. If the onAdLoadFailed event is generated, the reason is indicated by the InMobiAdRequestStatus object passed in this event. If the onAdLoadSucceeded event is generated, you may now show the ad anytime after this by calling show() on the InMobiInterstitial instance.

    Note: Calling load() on the same interstitial ad after the onAdLoadSucceeded event is generated by the SDK is not guaranteed to request a fresh ad from the network. A fresh ad will only be fetched if either the previous ad was discarded by the SDK, or if the ad expired or the user cleared application data and caches.

    Showing a Rewarded Video Ad

    To show a rewarded video ad, just call show() on the InMobiInterstitial instance anytime after the onAdLoadSucceeded event has been generated by the SDK. The code fragment below illustrates this:

     InterstitialAdEventListener mInterstitialAdEventListener = new InterstitialAdEventListener() {
            // implementation for other events
            // onAdReceived, onAdLoaFailed, etc
    
            @Override
            public void onAdLoadSucceeded(InMobiInterstitial inMobiInterstitial) {
                Log.d(TAG, "Ad can now be shown!");
                mCanShowAd = true;
            }
        };
    
       void init() {
           InMobiInterstitial interstitialAd = new InMobiInterstitial(GameActivity.this, 1471550843414L, mInterstitialAdEventListener);
       }
    
       void prepareGameLevel() {
           interstitialAd.load();
       }
    
       void handleGameLevelCompleted() {
            If (mCanShowAd) interstitialAd.show();
       }
    	

    Your application will be notified of the result of this request via the InterstitialAdEventListener’s callbacks. If the ad can be shown, then the SDK will notify your code by calling on the onAdWillDisplay interface, followed by calling the onAdDisplayed method when the ad is actually presented on the screen. If the ad cannot be displayed, the onAdDisplayFailed event is generated by the SDK to let your application know that the ad could not be displayed. You can request for a fresh ad by calling load() again to handle this event.

    When an interstitial ad is dismissed, your application will be notified in the onAdDismissed callback.

    Animations

    You can animate the presenting and dismissing of the interstitial ad by supplying animation resource IDs to be used in this process. This is done simply by calling the show(int, int) variant like so:

    interstitialAd.show(R.anim.anim_entry, R.anim.anim_exit);

    Implementing the Callback for Rewards

    For rewarded video ads, the SDK will generate the onAdRewardActionCompleted event, passing the meta data you configured on the InMobi support portal. You can handle this event like so:

      InterstitialAdEventListener mInterstitialAdEventListener = new InterstitialAdEventListener() {
            // implementation for other events
            // onAdLoadSucceeded, onAdDisplayed, etc
            @Override
            public void onAdRewardActionCompleted(InMobiInterstitial inMobiInterstitial, Map<Object, Object> map) {
                Log.d(TAG, "Ad rewards unlocked!");
                for (Object key : map.keySet()) {
                    Object value = map.get(key);
                    Log.v(TAG, "Unlocked " + value + " " + key);
                }
            }
        };

    You can check the code samples for interstitial ad integrations on GitHub here.

    Retrieving CreativeID

    At times, there are rogue advertisers who escape all the ad quality checks and end up compromising the user experience on the app by showcasing either an irrelevant, distasteful or disrupting creative to the user. To combat such situations, you can retrieve the creativeID of the ad instance and report back to your InMobi point of contact with the encrypted creativeID.

    mInterstitialAd.getCreativeId()// mInterstitialAd is an example instance.

    Testing the Integration

    1. Configure the test mode on InMobi portal.

      Go to Tools - Diagnostics and switch Test Mode to either Global ON or Selective ON.

      If you are integrating an ad unit for the first time Set Test Mode to Global ON.
      If you want to selectively turn on test traffic for a set of devices:


      Note: You already have a prior version of the SDK integrated for this particular ad unit and therefore you should restrict your testing to only few devices
      Set Test Mode to Selective ON.

      In the device section:

      1. In the Device ID box, type the device ID.
      2. In the Device Name box, set any name.
      3. Click Add Device to add the test device.

      If you already have a device configured, you can select the device and test mode will be enabled.

      Note: You MUST turn off the test mode before going live or else your app will fail to monetize.

      Now you are all set to get test ads.

      Getting the Device ID

      The device id is the Google Play Advertising ID (GPID). To get the device ID, configure the SDK to print debug logs to the console. You can do so by adding the following line to your Activity where you are integrating rewarded video ads.

      InMobiSdk.setLogLevel(LogLevel.DEBUG);

      The device ID will now be printed in debug logs in the DDMS console like so:

    2. You will also get feedback on the diagnostics tab on the ad unit and ad request and this can be particularly helpful during integration.


    Helpful Debug Information

    Once you have enabled debug logs as mentioned in step 1, SDK will print key logs to the DDMS console that provide useful information about the initialization and ad load lifecycle.

    The following tables capture these logs.

    SDK Initialization
    Scenario Log Level Log message
    Publisher passed null or empty account id Error Account id cannot be null or empty. Please provide a valid Account id.
    Publisher passed a valid account id Debug InMobi SDK initialized with account id: <account id>
    Publisher Passed an invalid account Id Error Invalid account id passed to init. Please provide a valid account id.
    Publisher did not grant the mandatory permissions Debug Please grant the mandatory permissions : INTERNET & ACCESS_NETWORK_STATE, SDK could not be initialized.
    Permissions granted to the SDK Debug Permissions granted to the SDK are :<List of permissions granted>
    Newer version of SDK is available Debug A newer version (ver. 9.0.0) of the InMobi SDK is available! You are currently on an older version (ver. 5.3.1). Download the latest InMobi SDK from http://www.inmobi.com/products/sdk/#downloads

    Common Ad Lifecycle Messages
    Scenario Log Level Log message
    Ad requested when no network available Error LogLevel Network not reachable currently. Please try again.
    Ad requested when ad state is loading or available Error LogLevel An ad load is already in progress. Please wait for the load to complete before requesting for another ad (Placement id : <placement id> ).
    Ad requested when ad is viewed by user Error LogLevel An ad is currently being viewed by the user. Please wait for the user to close the ad before requesting for another ad (Placement id : <placement id> ).
    Publisher device Id Debug LogLevel Publisher device id is <Device Id>
    Requested ad being returned from cache   Returning ad from cache for the Placement Id - <Placement Id>
    Requested ad being fetched from network   Ad will be fetched from network for the Placement Id - <Placement Id>

    Messages for Rewarded Video Ad Integrations
    Scenario Log Level Log message
    Publisher created an interstitial without initializing the SDK Error Please initialize the SDK before creating an interstitial ad
    Publisher called load on interstitial Debug Fetching an interstitial ad for placement id: <placement id>
    Successfully fetched ad Debug Interstitial ad successfully fetched for placement id: <Placement id>
    Failed to fetch the ad Error Failed to fetch interstitial ad for placement id:<Placement id> with error: <Status code / message>
    Started loading the interstitial in a webview Debug Started loading interstitial ad markup in the webview for placement id: <Placement id>
    Interstitial successfully loaded in the webview Debug Successfully loaded interstitial ad markup in the webview for placement id: <placement id>
    Failed to load interstitial in the webview Error Failed to load interstitial markup in the webview for placement id: <placement id>
    Failed to load interstitial in the webview due to timeout Error Failed to load interstitial markup in the webview due to timeout for placement id: <placement id>
    Interstitial Ad displayed Debug Successfully displayed Interstitial for placement id:<placement id>
    Interstitial Ad dismissed Debug Interstitial ad dismissed for placement id:<placement id>
    No Listener specified Set Listener to null in constructor Error The Ad unit cannot be created as no event listener was supplied. Please attach a listener to proceed
    Null context Set Context to null in constructor Error Unable to create ad unit with NULL context object
    Ad show before ready Show ad before it's ready Error Ad Load is not complete. Please wait for the Ad to be in a ready state before calling show The supplied resource id with show for animations is invalid
    InMobiAdActivity not added Error Do not declare InMobiAdActivity in manifest file.

    In addition to logs printed by the SDK, you can also get feedback on the diagnostics tab on the ad unit and ad request, which can be particularly helpful during integration.

    exchange | Android Full test

    Full-screen video ads are short (15-30 sec), skippable videos, which help in monetization with high eCPMs. Preferred by brands and game developers, these are perfect for happy moments such as level wins and wait times in Player vs Player (PVP). Video ads leverage the power of sight, sound, and motion to create immersive experiences for the user thereby enhancing the in-app ad experience.

    To create a video ad, you need to start with an interstitial ad placement. Once you have an interstitial ad placement, you have controls on the InMobi portal to either run a mix of static and video ads or video only.

    You also have access to advanced video controls on whether you want to run skippable video ads and only when the user is on Wifi.

    Follow these simple steps and start monetizing with Video ads:

    Setting up a Full-screen Video Ad

    1. To display a full screen video ad, you need an interstitial placement ID.
    2. After adding your app, select INTERSTITIAL AD to create a placement for ad type Interstitial.
    3. Once you successfully create the placement, the placement ID is available.

    Adding a Full-screen Video Ad to your App

    Creating a Full-screen Video Ad

    To create an interstitial ad, create an instance of an InMobiInterstitial like so:

    InMobiInterstitial interstitialAd = new InMobiInterstitial(InterstitialAdsActivity.this, 1471550843414L, mInterstitialAdListener);
    	

    Here, mInterstitialAdListener is an implementation of the InterstitialAdEventListener abstract class. It is mandatory to supply an implementation of this interface to create an interstitial ad.

    Note: The InMobiInterstitial class is not thread-safe. An interstitial instance must be created on the UI thread. Similarly, all methods on this instance must be called on the UI thread. Not doing so will lead to unpredictable behavior and may affect your ability to monetize with InMobi.

    The InterstitialAdListener2 interface allows you to listen to key lifecycle events for an interstitial ad. You should listen to these events to ensure that your application correctly handles the various lifecycle transitions.

       /**
    * Listener for receiving notifications during the lifecycle of an interstitial.
    */
    public abstract class InterstitialAdEventListener {
       /**
        * Called to indicate that an ad was loaded and it can now be shown. This will always be called
        * after the {@link #onAdReceived(InMobiInterstitial)} callback.
        *
        * @param ad Represents the {@link InMobiInterstitial} ad which was loaded
        */
       public void onAdLoadSucceeded(InMobiInterstitial ad) {}
    
       /**
        * Callback to signal that a request to fetch an ad (by calling
        * {@link InMobiInterstitial#load()} failed. The status code indicating the reason for failure
        * is available as a parameter. You should call {@link InMobiInterstitial#load()} again to
        * request a fresh ad.
        *
        * @param ad Represents the {@link InMobiInterstitial} ad which failed to load
        * @param status Represents the {@link InMobiAdRequestStatus} status containing error reason
        */
       public void onAdLoadFailed(InMobiInterstitial ad, InMobiAdRequestStatus status) {}
    
       /**
        * Called to indicate that an ad is available in response to a request for an ad (by calling
        * {@link InMobiInterstitial#load()}. 

    Note This does not * indicate that the ad can be shown yet. Your code should show an ad after the * {@link #onAdLoadSucceeded(InMobiInterstitial)} method is called. Alternately, if you do not * want to handle this event, you must test if the ad is ready to be shown by checking the * result of calling the {@link InMobiInterstitial#isReady()} method.

    * * @param ad Represents the {@link InMobiInterstitial} ad for which ad content was received */ public void onAdReceived(InMobiInterstitial ad) {} /** * Called to indicate that an ad interaction was observed. * * @param ad Represents the {@link InMobiInterstitial} ad on which user clicked * @param params Represents the click parameters */ public void onAdClicked(InMobiInterstitial ad, Map params) {} /** * Called to indicate that the ad will be launching a fullscreen overlay. * * @param ad Represents the {@link InMobiInterstitial} ad which will display */ public void onAdWillDisplay(InMobiInterstitial ad) {} /** * Called to indicate that the fullscreen overlay is now the topmost screen. * * @param ad Represents the {@link InMobiInterstitial} ad which is displayed */ public void onAdDisplayed(InMobiInterstitial ad) {} /** * Called to indicate that a request to show an ad (by calling {@link InMobiInterstitial#show()} * failed. You should call {@link InMobiInterstitial#load()} to request for a fresh ad. * * @param ad Represents the {@link InMobiInterstitial} ad which failed to show */ public void onAdDisplayFailed(InMobiInterstitial ad) {} /** * Called to indicate that the fullscreen overlay opened by the ad was closed. * * @param ad Represents the {@link InMobiInterstitial} ad which was dismissed */ public void onAdDismissed(InMobiInterstitial ad) {} /** * Called to indicate that the user may leave the application on account of interacting with the ad. * * @param ad Represents the {@link InMobiInterstitial} ad */ public void onUserLeftApplication(InMobiInterstitial ad) {} /** * Called to indicate that rewards have been unlocked. * * @param ad Represents the {@link InMobiInterstitial} ad for which rewards was unlocked * @param rewards Represents the rewards unlocked */ public void onRewardsUnlocked(InMobiInterstitial ad, Map rewards) {} }

    Loading a Full-screen Video Ad

    To request for an interstitial ad, call the load() method on the InMobiInterstitial instance like so:

    interstitialAd.load();

    You will be notified of the result of this method via the InterstitialAdEventListener abstract class. If the ad request was successful, the onAdReceived(InMobiInterstitial) event will be generated. This will be followed by either the onAdLoadSucceeded or the onAdLoadFailed event. If the onAdLoadFailed event is generated, the reason is indicated by the InMobiAdRequestStatus object passed in this event. If the onAdLoadSucceeded event is generated, you may now show the ad anytime after this by calling show() on the InMobiInterstitial instance.

    Note: Calling load() on the same interstitial ad after the onAdLoadSucceeded event is generated by the SDK is not guaranteed to request a fresh ad from the network. A fresh ad will only be fetched if either the previous ad was discarded by the SDK, or if the ad expired or the User cleared application data and caches.

    Showing a Full-screen Video Ad

    To show an interstitial ad, just call show() on the InMobiInterstitial instance anytime after the onAdLoadSucceeded event has been generated by the SDK. The code fragment below illustrates this:

        InterstitialAdEventListener mInterstitialAdEventListener = new InterstitialAdEventListener() {
            // implementation for other events
            // onAdReceived, onAdLoaFailed, etc
    
            @Override
            public void onAdLoadSucceeded(InMobiInterstitial inMobiInterstitial) {
                Log.d(TAG, "Ad can now be shown!");
                mCanShowAd = true;
            }
        };
    
       void init() {
           InMobiInterstitial interstitialAd = new InMobiInterstitial(GameActivity.this, 1471550843414L, mInterstitialAdEventListener);
       }
    
       void prepareGameLevel() {
           interstitialAd.load();
       }
    
       void handleGameLevelCompleted() {
            If (mCanShowAd) interstitialAd.show();
       }
      

    Your application will be notified of the result of this request via the InterstitialAdEventListener abstract class. If the ad can be shown, the SDK will notify your code by calling on the onAdWillDisplay interface, followed by calling the onAdDisplayed method when the ad is actually presented on the screen. If the ad cannot be displayed, the onAdDisplayFailed event is generated by the SDK to let your application know that the ad could not be displayed. You can request for a fresh ad by calling load() again to handle this event.

    When an interstitial ad is dismissed, your application will be notified in the onAdDismissed callback.

    Animations

    You can animate the presenting and dismissing of the interstitial ad by supplying animation resource IDs to be used in this process. This is done simply by calling the show(int, int) variant:

    interstitialAd.show(R.anim.anim_entry, R.anim.anim_exit);

    You can check the code samples for interstitial ad integrations on GitHub here.

    Retrieving CreativeID

    At times, there are rogue advertisers who escape all the ad quality checks and end up compromising the user experience on the app by showcasing either an irrelevant, distasteful or disrupting creative to the user. To combat such situations, you can retrieve the creativeID of the ad instance and report back to your InMobi point of contact with the encrypted creativeID.

    mInterstitialAd.getCreativeId()// mInterstitialAd is an example instance.

    Testing the Integration

    1. Configure the test mode on InMobi portal.

      Go to Tools - Diagnostics and switch Test Mode to either Global ON or Selective ON.

      If you are integrating an ad unit for the first time Set Test Mode to Global ON.
      If you want to selectively turn on test traffic for a set of devices:


      Note: You already have a prior version of the SDK integrated for this particular ad unit and therefore you should restrict your testing to only few devices
      Set Test Mode to Selective ON.

      In the device section:

      1. In the Device ID box, type the device ID.
      2. In the Device Name box, set any name.
      3. Click Add Device to add the test device.

      If you already have a device configured, you can select the device and test mode will be enabled.

      Note: You MUST turn off the test mode before going live or else your app will fail to monetize.

      Now you are all set to get test ads.

      Getting the Device ID

      The device id is the Google Play Advertising ID (GPID). To get the device ID, configure the SDK to print debug logs to the console. You can do so by adding the following line to your Activity where you are integrating full-screen video ads.

      InMobiSdk.setLogLevel(LogLevel.DEBUG);

      The device ID will now be printed in debug logs in the DDMS console like so:

    2. You will also get feedback on the diagnostics tab on the ad unit and ad request and this can be particularly helpful during integration.

    Helpful Debug Information

    Once you have enabled debug logs as mentioned in step 1, SDK will print key logs to the DDMS console that provide useful information about the initialization and ad load lifecycle. The following tables capture these logs.


    SDK Initialization
    Scenario Log Level Log message
    Publisher passed null or empty account id Error Account id cannot be null or empty. Please provide a valid Account id.
    Publisher passed a valid account id Debug InMobi SDK initialized with account id: <account id>
    Publisher Passed an invalid account Id Error Invalid account id passed to init. Please provide a valid account id.
    Publisher did not grant the mandatory permissions Debug Please grant the mandatory permissions : INTERNET & ACCESS_NETWORK_STATE, SDK could not be initialized.
    Permissions granted to the SDK Debug Permissions granted to the SDK are :<List of permissions granted>
    Newer version of SDK is available Debug A newer version (ver. 9.0.0) of the InMobi SDK is available! You are currently on an older version (ver. 5.3.1). Download the latest InMobi SDK from http://www.inmobi.com/products/sdk/#downloads

    Common Ad Lifecycle Messages
    Scenario Log Level Log message
    Ad requested when no network available Error LogLevel Network not reachable currently. Please try again.
    Ad requested when ad state is loading or available Error LogLevel An ad load is already in progress. Please wait for the load to complete before requesting for another ad (Placement id : <placement id> ).
    Ad requested when ad is viewed by user Error LogLevel An ad is currently being viewed by the user. Please wait for the user to close the ad before requesting for another ad (Placement id : <placement id> ).
    Publisher device Id Debug LogLevel Publisher device id is <Device Id>
    Requested ad being returned from cache   Returning ad from cache for the Placement Id - <Placement Id>
    Requested ad being fetched from network   Ad will be fetched from network for the Placement Id - <Placement Id>

    Messages for Full-screen Video Ad Integrations
    Scenario Log Level Log message
    Publisher created an interstitial without initializing the SDK Error Please initialize the SDK before creating an interstitial ad
    Publisher called load on interstitial Debug Fetching an interstitial ad for placement id: <placement id>
    Successfully fetched ad Debug Interstitial ad successfully fetched for placement id: <Placement id>
    Failed to fetch the ad Error Failed to fetch interstitial ad for placement id:<Placement id> with error: <Status code / message>
    Started loading the interstitial in a webview Debug Started loading interstitial ad markup in the webview for placement id: <Placement id>
    Interstitial successfully loaded in the webview Debug Successfully loaded interstitial ad markup in the webview for placement id: <placement id>
    Failed to load interstitial in the webview Error Failed to load interstitial markup in the webview for placement id: <placement id>
    Failed to load interstitial in the webview due to timeout Error Failed to load interstitial markup in the webview due to timeout for placement id: <placement id>
    Interstitial Ad displayed Debug Successfully displayed Interstitial for placement id:<placement id>
    Interstitial Ad dismissed Debug Interstitial ad dismissed for placement id:<placement id>
    No Listener specified Set Listener to null in constructor Error The Ad unit cannot be created as no event listener was supplied. Please attach a listener to proceed
    Null context Set Context to null in constructor Error Unable to create ad unit with NULL context object
    Ad show before ready Show ad before it's ready Error Ad Load is not complete. Please wait for the Ad to be in a ready state before calling show The supplied resource id with show for animations is invalid
    InMobiAdActivity not added Error Do not declare InMobiAdActivity in manifest file.

    In addition to logs printed by the SDK, you can also get feedback on the diagnostics tab on the ad unit and ad request, which can be particularly helpful during integration.

    exchange | Android Inter test

    Interstitial ads are full page ads placed at natural break points in the app flow. With 10 times the real estate as compared to banner ads, Interstitials are guaranteed to catch your users' eyes and drive higher revenue for your mobile business.

    Follow these simple steps and start monetizing with Interstitial ads:

    Setting up an Interstitial Ad

      1. To display an Interstitial ad, you need an interstitial placement ID.
      2. After adding your app, select INTERSTITIAL AD to create a placement for ad type Interstitial.
      3. Once you successfully create the placement, the placement ID is available.

    Adding an Interstitial Ad to your App

    Creating an Interstitial Ad

    To create an interstitial ad, create an instance of an InMobiInterstitial:

    InMobiInterstitial interstitialAd = new InMobiInterstitial(InterstitialAdsActivity.this, 1471550843414L, mInterstitialAdEventListener);
    	

    Here, mInterstitialAdListener is an implementation of the InterstitialAdEventListener Abstract class. It is mandatory to supply an implementation of this abstract class to create an interstitial ad.

    Notes:

    • The InMobiInterstitial class is not thread-safe. An interstitial instance must be created on the UI thread.
    • Similarly, all methods on this instance must be called on the UI thread. Not doing so will lead to unpredictable behavior and may affect your ability to monetize with InMobi.

    InterstitialAdEventListener abstract class allows you to listen to key lifecycle events for an interstitial ad. You should listen to these events to ensure that your application correctly handles the various lifecycle transitions.

      /**
    * Listener for receiving notifications during the lifecycle of an interstitial.
    */
    public abstract class InterstitialAdEventListener {
       /**
        * Called to indicate that an ad was loaded and it can now be shown. This will always be called
        * <strong>after</strong> the {@link #onAdReceived(InMobiInterstitial)} callback.
        *
        * @param ad Represents the {@link InMobiInterstitial} ad which was loaded
        */
       public void onAdLoadSucceeded(InMobiInterstitial ad) {}
       /**
        * Callback to signal that a request to fetch an ad (by calling
        * {@link InMobiInterstitial#load()} failed. The status code indicating the reason for failure
        * is available as a parameter. You should call {@link InMobiInterstitial#load()} again to
        * request a fresh ad.
        *
        * @param ad Represents the {@link InMobiInterstitial} ad which failed to load
        * @param status Represents the {@link InMobiAdRequestStatus} status containing error reason
        */
       public void onAdLoadFailed(InMobiInterstitial ad, InMobiAdRequestStatus status) {}
       /**
        * Called to indicate that an ad is available in response to a request for an ad (by calling
        * {@link InMobiInterstitial#load()}. <p class="note"><strong>Note</strong> This does not
        * indicate that the ad can be shown yet. Your code should show an ad <strong>after</strong> the
        * {@link #onAdLoadSucceeded(InMobiInterstitial)} method is called. Alternately, if you do not
        * want to handle this event, you must test if the ad is ready to be shown by checking the
        * result of calling the {@link InMobiInterstitial#isReady()} method.</p>
        *
        * @param ad Represents the {@link InMobiInterstitial} ad for which ad content was received
        */
       public void onAdReceived(InMobiInterstitial ad) {}
       /**
        * Called to indicate that an ad interaction was observed.
        *
        * @param ad Represents the {@link InMobiInterstitial} ad on which user clicked
        * @param params Represents the click parameters
        */
       public void onAdClicked(InMobiInterstitial ad, Map<Object, Object> params) {}
       /**
        * Called to indicate that the ad will be launching a fullscreen overlay.
        *
        * @param ad Represents the {@link InMobiInterstitial} ad which will display
        */
       public void onAdWillDisplay(InMobiInterstitial ad) {}
       /**
        * Called to indicate that the fullscreen overlay is now the topmost screen.
        *
        * @param ad Represents the {@link InMobiInterstitial} ad which is displayed
        */
       public void onAdDisplayed(InMobiInterstitial ad) {}
       /**
        * Called to indicate that a request to show an ad (by calling {@link InMobiInterstitial#show()}
        * failed. You should call {@link InMobiInterstitial#load()} to request for a fresh ad.
        *
        * @param ad Represents the {@link InMobiInterstitial} ad which failed to show
        */
       public void onAdDisplayFailed(InMobiInterstitial ad) {}
       /**
        * Called to indicate that the fullscreen overlay opened by the ad was closed.
        *
        * @param ad Represents the {@link InMobiInterstitial} ad which was dismissed
        */
       public void onAdDismissed(InMobiInterstitial ad) {}
       /**
        * Called to indicate that the user may leave the application on account of interacting with the ad.
        *
        * @param ad Represents the {@link InMobiInterstitial} ad
        */
       public void onUserLeftApplication(InMobiInterstitial ad) {}
       /**
        * Called to indicate that rewards have been unlocked.
        *
        * @param ad Represents the {@link InMobiInterstitial} ad for which rewards was unlocked
        * @param rewards Represents the rewards unlocked
        */
       public void onRewardsUnlocked(InMobiInterstitial ad, Map<Object, Object> rewards) {}
    }
    	

    Loading an Interstitial Ad

    To request for an interstitial ad, call the load() method on the InMobiInterstitial instance:

    interstitialAd.load();
    	

    InterstitialAdEventListener abstract class notifies the result of this method. If the ad request was successful, the onAdReceived(InMobiInterstitial) event is generated. This is followed by either the onAdLoadSucceeded or the onAdLoadFailed event.

    If the onAdLoadFailed event is generated, the reason is indicated by the InMobiAdRequestStatus object passed in this event.

    If the onAdLoadSucceeded event is generated, you can show the ad anytime after this by calling show() on the InMobiInterstitial instance.

    Note: Calling load() on the same interstitial ad after the onAdLoadSucceeded event is generated by the SDK is not guaranteed to request a fresh ad from the network. A fresh ad will only be fetched if either the previous ad was discarded by the SDK, or if the ad expired or the user cleared application data and caches.

    Showing an Interstitial Ad

    To show an interstitial ad, call show() on the InMobiInterstitial instance anytime after the onAdLoadSucceeded event has been generated by the SDK. The code fragment below illustrates the same.

        InterstitialAdEventListener mInterstitialAdEventListener = new InterstitialAdEventListener
    () {
            // implementation for other events
            // onAdReceived, onAdLoaFailed, etc
    
            @Override
            public void onAdLoadSucceeded(InMobiInterstitial inMobiInterstitial) {
                Log.d(TAG, "Ad can now be shown!");
                mCanShowAd = true;
            }
        };
    
       void init() {
           InMobiInterstitial interstitialAd = new InMobiInterstitial(GameActivity.this, 1471550843414L, mInterstitialAdEventListener);
       }
    
       void prepareGameLevel() {
           interstitialAd.load();
       }
    
       void handleGameLevelCompleted() {
            If (mCanShowAd) interstitialAd.show();
       }
    	

    Your application will be notified of the result of this request via the InterstitialAdEventListener abstract class.

    If the ad can be shown, the SDK will notify your code by calling on the onAdWillDisplay interface, followed by calling the onAdDisplayed method when the ad is actually presented on the screen.

    If the ad cannot be displayed, the onAdDisplayFailed event is generated by the SDK to let your application know that the ad could not be displayed. You can request for a fresh ad by calling load() again to handle this event.

    When an interstitial ad is dismissed, your application will be notified in the onAdDismissed callback.

    Animations

    You can animate the presenting and dismissing of the interstitial ad by supplying animation resource IDs to be used in this process. This is done simply by calling the show(int, int) variant like so:

    interstitialAd.show(R.anim.anim_entry, R.anim.anim_exit);
    	

    You can check the code samples for interstitial ad integrations on GitHub here.

    Retrieving CreativeID

    At times, there are rogue advertisers who escape all the ad quality checks and end up compromising the user experience on the app by showcasing either an irrelevant, distasteful or disrupting creative to the user. To combat such situations, you can retrieve the creativeID of the ad instance and report back to your InMobi point of contact with the encrypted creativeID.

    mInterstitialAd.getCreativeId()// mInterstitialAd is an example instance.

    Testing the Integration

    1. Configure the test mode on InMobi portal.

      Go to Tools - Diagnostics and switch Test Mode to either Global ON or Selective ON.

      If you are integrating an ad unit for the first time Set Test Mode to Global ON.
      If you want to selectively turn on test traffic for a set of devices:


      Note: You already have a prior version of the SDK integrated for this particular ad unit and therefore you should restrict your testing to only few devices
      Set Test Mode to Selective ON.

      In the device section:

      1. In the Device ID box, type the device ID.
      2. In the Device Name box, set any name.
      3. Click Add Device to add the test device.

      If you already have a device configured, you can select the device and test mode will be enabled.

      Note: You MUST turn off the test mode before going live or else your app will fail to monetize.

      Now you are all set to get test ads.

      Getting the Device ID

      The device id is the Google Play Advertising ID (GPID). To get the device ID, configure the SDK to print debug logs to the console. You can do so by adding the following line to your Activity where you are integrating interstitial ads.

      InMobiSdk.setLogLevel(LogLevel.DEBUG);
      		

      The device ID will now be printed in debug logs in the DDMS console:

    2. You will also get feedback on the diagnostics tab on the ad unit and ad request and this can be particularly helpful during integration.

    Helpful Debug Information

    Once you have enabled debug logs as mentioned in step 1, SDK will print key logs to the DDMS console that provide useful information about the initialization and ad load lifecycle.

    The following tables capture these logs.

    SDK Initialization
    Scenario Log Level Log message
    Publisher passed null or empty account id Error Account id cannot be null or empty. Please provide a valid Account id.
    Publisher passed a valid account id Debug InMobi SDK initialized with account id: <account id>
    Publisher Passed an invalid account Id Error Invalid account id passed to init. Please provide a valid account id.
    Permissions granted to the SDK Debug Permissions granted to the SDK are :<List of permissions granted>
    Newer version of SDK is available Debug A newer version (ver. 9.0.0) of the InMobi SDK is available! You are currently on an older version (ver. 5.3.1). Download the latest InMobi SDK from http://www.inmobi.com/products/sdk/#downloads
    Common Ad Lifecycle Messages
    Scenario Log Level Log message
    Ad requested when no network available Error LogLevel Network not reachable currently. Please try again.
    Ad requested when ad state is loading or available Error LogLevel An ad load is already in progress. Please wait for the load to complete before requesting for another ad (Placement id : <placement id> ).
    Ad requested when ad is viewed by user Error LogLevel An ad is currently being viewed by the user. Please wait for the user to close the ad before requesting for another ad (Placement id : <placement id> ).
    Publisher device Id Debug LogLevel Publisher device id is <Device Id>
    Requested ad being fetched from network   Ad will be fetched from network for the Placement Id - <Placement Id>
    Messages for Interstitial Ad Integrations
    Scenario Log Level Log message
    Publisher created an interstitial without initializing the SDK Error Please initialize the SDK before creating an interstitial ad
    Publisher called load on interstitial Debug Fetching an interstitial ad for placement id: <placement id>
    Successfully fetched ad Debug Interstitial ad successfully fetched for placement id: <Placement id>
    Failed to fetch the ad Error Failed to fetch interstitial ad for placement id:<Placement id> with error: <Status code / message>
    Started loading the interstitial in a webview Debug Started loading interstitial ad markup in the webview for placement id: <Placement id>
    Interstitial successfully loaded in the webview Debug Successfully loaded interstitial ad markup in the webview for placement id: <placement id>
    Failed to load interstitial in the webview Error Failed to load interstitial markup in the webview for placement id: <placement id>
    Failed to load interstitial in the webview due to timeout Error Failed to load interstitial markup in the webview due to timeout for placement id: <placement id>
    Interstitial Ad displayed Debug Successfully displayed Interstitial for placement id:<placement id>
    Interstitial Ad dismissed Debug Interstitial ad dismissed for placement id:<placement id>
    No Listener specified Set Listener to null in constructor Error The Ad unit cannot be created as no event listener was supplied. Please attach a listener to proceed
    Null context Set Context to null in constructor Error Unable to create ad unit with NULL context object
    Ad show before ready Show ad before it's ready Error Ad Load is not complete. Please wait for the Ad to be in a ready state before calling show.

    In addition to logs printed by the SDK, you can also get feedback on the diagnostics tab on the ad unit and ad request, which can be particularly helpful during integration.

    exchange | Android Banner test

    It is one of the most dominant forms of advertising on the internet. Banner ads are a form of display advertising that can range from a static graphic to full motion video.

    Follow these simple steps and start monetizing with Banner ads:

    Setting up a Banner Ad

    To display a banner ad on your app, you would first need to create a banner placement ID. After adding your app, select BANNER AD to create a placement for the ad type - Banner. Once you create the banner placement, the placement ID is available.

    Adding a Banner Ad to your App

    Creating a Banner Ad

    Option 1: Adding a Banner in XML layout resource files

    You can add a banner ad in your layout resource file in XML and reference it in your code as you would in a regular view.

    The following snippet shows how to add a banner ad in XML. Note the inmobi ads namespace that you need to add to the top-level layout element to add the banner.

    <LinearLayout 
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:ads="http://schemas.android.com/apk/lib/com.inmobi.ads"
        xmlns:tools="http://schemas.android.com/tools" 
        android:layout_width="match_parent"
        android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        android:paddingBottom="@dimen/activity_vertical_margin"
        android:orientation="vertical"
        tools:context="com.inmobi.samples.BannerXMLActivity">
        <TextView android:text="@string/banner_xml_message"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
        <com.inmobi.ads.InMobiBanner
            android:layout_width="320dp"
            android:layout_height="50dp"
            android:id="@+id/banner"
            ads:placementId="plid-1431977751489005"
            ads:refreshInterval="60"
        />
    </LinearLayout>
    	

    Note: For banner XML integration, publishers using Android SDK 720 and onwards needs to append “plid-” to placementId TAG as following:

    ads:placementId="plid-1431977751489005"
    	

    Now, you can reference the banner in your code:

    InMobiBanner bannerAd = (InMobiBanner)findViewById(R.id.banner);
    	

    Once you have the banner instance, you can request for ads to be loaded as shown in the following sections.

    Before you do that, call the InMobiSdk.init(Context, String) method in your main activity or the activity where you are displaying banner ad to initialize the InMobi SDK.

    Option 2: Adding a Banner in code

    To add a banner ad in Android code, create an instance of InMobiBanner:

    InMobiBanner bannerAd = new InMobiBanner(BannerAdsActivity.this, 1468078426600L);
    	

    Notes:

    • The <strong>InMobiBanner</strong> class is not thread-safe. A banner instance must be created on the UI thread.
    • Similarly, all methods on this instance must be called on the UI thread. Not doing so will lead to unpredictable behavior and may affect your ability to monetize with InMobi.

    Once you have created a banner ad, you can add it to the view hierarchy:

    RelativeLayout adContainer = (RelativeLayout) findViewById(R.id.ad_container);
    RelativeLayout.LayoutParams bannerLp = new RelativeLayout.LayoutParams(<WIDTH_IN_PIXEL>, <HEIGHT_IN_PIXEL>);
    bannerLp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
    bannerLp.addRule(RelativeLayout.CENTER_HORIZONTAL);
    adContainer.addView(bannerAd, bannerLayoutParams);
    	

    Note:

    • You should specify the banner view dimensions in pixel units when setting the layout parameters for the banner ad.
    • Also, it is a programming error to supply WRAP_CONTENT as the layout parameters for a banner ad. This constraint applies whether you create a banner in your XML layout resource file or in code.
    • If you are building for both phones and tablets, you can supply MATCH_PARENT as the layout parameters for the banner. The InMobi SDK will correctly compute the banner view dimensions and use them to fetch an ad from the InMobi Network.

    Loading a Banner Ad

    Loading a banner ad requires you to add the banner ad view to your view hierarchy before requesting for an ad on the InMobiBanner instance. Adding the view to the view hierarchy enables the InMobi SDK to correctly compute the banner view dimensions and to request for the best ad matching those dimensions from the network.

    Once you have added InMobiBanner to the view hierarchy, you can call the load() method on the instance you just created to request for an ad.

    Setting up Auto-refresh for your Banner Ad

    The banner ads refresh automatically after the first time you requested for an ad by calling <strong>load()</strong> on an InMobiBanner instance. You can set up auto-refresh either while creating a banner in XML layout resource file, or later in code, by calling the setRefreshInterval(int) method on a banner ad.

    The sample below shows how to do this in XML:

    <LinearLayout 
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:ads="http://schemas.android.com/apk/lib/com.inmobi.ads"
        xmlns:tools="http://schemas.android.com/tools" 
    android:layout_width="match_parent"
        android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        android:paddingBottom="@dimen/activity_vertical_margin"
        android:orientation="vertical"
        tools:context="com.inmobi.samples.BannerXMLActivity">
        <TextView android:text="@string/banner_xml_message"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
        <com.inmobi.ads.InMobiBanner
            android:layout_width="320dp"
            android:layout_height="50dp"
            android:id="@+id/banner"
            ads:placementId="plid-1431977751489005"
            ads:refreshInterval="60"
        />
    </LinearLayout>
    	

    Animating Banner Ad Refreshes

    You can choose an animation style that takes effect when a banner is refreshed. You can also choose to turn OFF any animation for banner refreshes.

    To do so, you can call the setAnimationType(InMobiBanner.AnimationType) method after obtaining a banner instance.

    Note: The default animation is set to AnimationType.ROTATE_HORIZONTAL_AXIS. If you want to turn this off, call the setAnimationType method with the AnimationType.ANIMATION_OFF parameter.

    Listening for Banner Ad Lifecycle Events

    If you want to listen for key events in the banner lifecycle, you should implement the BannerAdListener interface. You can then set this listener using the setListener(BannerAdListener) method on the InMobiBanner instance. A brief description of each event is as follows.

        /**
    * A listener for receiving notifications during the lifecycle of a banner ad.
    */
    public abstract class BannerAdEventListener {
       /**
        * Called to notify that an ad was successfully loaded.
        * @param ad Represents the {@link InMobiBanner} ad which was loaded
        */
       public void onAdLoadSucceeded(InMobiBanner ad) {}
       /**
        * Called to notify that a request to load an ad failed.
        * @param ad Represents the {@link InMobiBanner} ad which failed to load
        * @param status Represents the {@link InMobiAdRequestStatus} status containing error reason
        */
       public void onAdLoadFailed(InMobiBanner ad, InMobiAdRequestStatus status) {}
       /**
        * Called to notify that the user interacted with the ad.
        * @param ad Represents the {@link InMobiBanner} ad on which user clicked
        * @param params Represents the click parameters
        */
       public void onAdClicked(InMobiBanner ad, Map<Object, Object> params) {}
       /**
        * Called to notify that the banner ad was displayed
        * @param ad Represents the {@link InMobiBanner} ad which was displayed
        */
       public void onAdDisplayed(InMobiBanner ad) {}
       /**
        * Called to notify that the User is about to return to the application after closing the ad.
        * @param ad Represents the {@link InMobiBanner} ad which was closed
        */
       public void onAdDismissed(InMobiBanner ad) {}
       /**
        * Called to notify that the user is about to leave the application as a result of interacting with the ad.
        * @param ad Represents the {@link InMobiBanner} ad
        */
       public void onUserLeftApplication(InMobiBanner ad) {}
       /**
        * Called to notify that a reward was unlocked.
        * @param ad Represents the {@link InMobiBanner} ad for which rewards was unlocked
        * @param rewards Represents the rewards unlocked
        */
       public void onRewardsUnlocked(InMobiBanner ad, Map<Object, Object> rewards) {}
      }
    	

    You can check the code samples for banner ad integrations on GitHub here.

    Retrieving CreativeID

    At times, there are rogue advertisers who escape all the ad quality checks and end up compromising the user experience on the app by showcasing either an irrelevant, distasteful or disrupting creative to the user. To combat such situations, you can retrieve the creativeID of the ad instance and report back to your InMobi point of contact with the encrypted creativeID.

    mBannerAd.getCreativeId() // mBannerAd is an example instance.

    Destroying Banner

    If you’re done with the Banner object, then simply call destroy on the same to release the resources. This will do the following:

    1. Remove the ad-view from the view hierarchy
    2. Cancel any ongoing refresh
    3. De-reference the listeners
    4. Other clean-ups

    mBannerAd.destroy(); // mBannerAd is an example instance.

    Testing the Integration

    1. Configure the test mode on InMobi portal.

      Go to Tools - Diagnostics and switch Test Mode to either Global ON or Selective ON.

      If you are integrating an ad unit for the first time Set Test Mode to Global ON.
      If you want to selectively turn on test traffic for a set of devices:


      Note: You already have a prior version of the SDK integrated for this particular ad unit and therefore you should restrict your testing to only few devices
      Set Test Mode to Selective ON.

      In the device section:

      1. In the Device ID box, type the device ID.
      2. In the Device Name box, set any name.
      3. Click Add Device to add the test device.

      If you already have a device configured, you can select the device and test mode will be enabled.

      Note: You MUST turn off the test mode before going live or else your app will fail to monetize.

      Now you are all set to get test ads.

      Getting the Device ID

      The device id is the Google Play Advertising ID (GPID). To get the device ID, configure the SDK to print debug logs to the console.

      You can do so by adding the following line to your Activity where you are integrating banner ads.

      InMobiSdk.setLogLevel(LogLevel.DEBUG);
      		

      The device ID will now be printed in debug logs in the DDMS console:

    2. You will also get feedback on the diagnostics tab on the ad unit and ad request and this can be particularly helpful during integration.

    Helpful Debug Information

    Once you have enabled debug logs as mentioned in step 1, SDK will print key logs to the DDMS console that provide useful information about the initialization and ad load lifecycle.

    The following tables capture these logs.

    SDK Initialization
    Scenario Log Level Log message
    Publisher passed null or empty account id Error Account id cannot be null or empty. Please provide a valid Account id.
    Publisher passed a valid account id Debug InMobi SDK initialized with account id: <account id>
    Publisher passed an invalid account Id Error Invalid account id passed to init. Please provide a valid account id.
    Publisher didn't grant the mandatory permissions Debug Please grant the mandatory permissions : INTERNET & ACCESS_NETWORK_STATE, SDK could not be initialized.
    Permissions granted to the SDK Debug Permissions granted to the SDK are : <List of permissions granted>
    Newer version of SDK is available Debug A newer version (ver. 9.0.0) of the InMobi SDK is available! You are currently on an older version (ver. 5.3.1). Download the latest InMobi SDK from http://www.inmobi.com/products/sdk/#downloads
    Common Ad Lifecycle Messages
    Scenario Log Level Log message
    Ad requested when no network available Error LogLevel Network not reachable currently. Please try again.
    Ad requested when ad state is loading or available Error LogLevel An ad load is already in progress. Please wait for the load to complete before requesting for another ad (Placement id : <placement id> ).
    Ad requested when ad is viewed by user Error LogLevel An ad is currently being viewed by the user. Please wait for the user to close the ad before requesting for another ad (Placement id : <placement id> ).
    Publisher device Id Debug LogLevel Publisher device id is <Device Id>
    Requested ad being returned from cache Returning ad from cache for the Placement Id - <Placement Id>
    Requested ad being fetched from network Ad will be fetched from network for the Placement Id - <Placement Id>
    Messages for Banner Ad Integrations
    Scenario Log Level Log message
    Publisher created a banner without initializing the SDK Error Please initialize the SDK before creating a Banner ad
    Publisher created a banner with an invalid/null placement id Error
    Publisher called load on a banner from IB/xml with improper placement id Error Placement id value supplied in XML layout is not valid. Banner creation failed.
    For Banner created in XML, no placement id provided Error Placement id value is not supplied in XML layout. Banner creation failed.
    Publisher called load on a banner Debug Fetching a Banner ad for placement id: <placement id>
    Successfully fetched ad Debug Banner ad successfully fetched for placement id: <Placement id>
    Failed to fetch the ad Debug Failed to fetch Banner ad for placement id:<Placement id> with error: <Status code / message>
    Started loading the banner in a webview Debug Started loading Banner ad markup in the webview for placement id: <Placement id>
    Banner successfully loaded in the webview Debug Successfully loaded Banner ad markup in the webview for placement id: <placement id>
    Failed to load banner in the webview Debug NA
    Banner refresh is initiated Debug Initiating Banner refresh for placement id: <placement id>
    Invalid placement id Error Placement id value supplied in XML layout is not valid. Banner creation failed.
    invalid refresh interval Debug Refresh interval value supplied in XML layout is not valid. Falling back to default value.
    Null Context Error Context supplied as null, the ad unit can't be created.
    Layout params not set Error The layout params of the banner must be set before calling load
    Height or width set to WRAP_CONTENT Error The height or width of a Banner ad can't be WRAP_CONTENT
    Height or width not set Error The height or width of the banner cannot be determined
    Null listener Error Please pass a non-null listener to the banner.

    In addition to logs printed by the SDK, you can also get feedback on the diagnostics tab on the ad unit and ad request, which can be particularly helpful during integration.

    exchange | Android test

    Getting Started with Android SDK Integration