integration guide ios - Unity-Technologies/unity-ads GitHub Wiki

/* Title: Integration guide for iOS (Objective-C) Description: A guide to integrating the Unity Ads SDK for iOS
Sort: 1
*/

Overview

This guide covers basic integration for implementing Unity Ads in your made-with-Unity game.

  • If you are a Unity developer using C#, click here.
  • If you are an Android developer using Java, click here.
  • Click here for the iOS (Objective-C) API reference.

In this guide:

Basic ads implementation

Creating a Project in the Unity Developer Dashboard

If you don't have a Unity Developer (UDN) account yet, create one here. When you have an account, follow these steps to create a Unity Project:

  1. Log in to the Unified Dashboard.
  2. From the landing page, navigate to the Monetize service. Click Explore to launch the Monetize Dashboard.
  3. Select Projects from the navigation bar.
  4. Click the New Project button.

Locate your Project’s Game ID by selecting your Project, then selecting Project Settings from the navigation bar. From the Project Settings page, go to the Game IDs section. Copy the Apple App Store Game ID, because you need it to activate the Unity Ads service in your game.

Creating Ad Units in your game

Ad Units are surfacing points that trigger ads in your game. Create Ad Units in the Monetize Dashboard by selecting your project, then selecting Monetization > Ad Units from the navigation bar.

Click the Add Ad Unit button to bring up the creation modal. Enter your Ad Unit ID and select its type:

  • Select Rewarded video to allow players to opt-in to viewing ads in exchange for incentives. Rewarded Ad Units do not allow the player to skip the ad.
  • Select Interstitial video to show basic interstitial ads or promotional content. Interstitial Ad Units allow players to skip the ad after a specified period of time.
  • Select Banner to create a dedicated Banner Ad Unit.

Every Unity Ads-enabled project has one Ad Unit for each format (rewarded, interstitial, and banner) per platform by default. Feel free to use one of these for your first implementation if they suit your needs, or create your own.

For more information, see documentation on Ad Units.

Importing the Unity Ads framework

Download the Unity Ads framework here. There are currently multiple ways to integrate the Unity Ads framework:

  • Using Cocoa Pods for UnityAds
  • Dragging and dropping the framework into your workspace.
  • Downloading the framework, then pointing XCode to the proper directory (this requires setting Framework Search Paths and Header Search Paths properties in your Build Settings)

Modifying the properties list

Games targeting users running iOS 14 or above must implement Unity Ads' network ID in the information property list file (Info.plist). For more information on how to do this, please see the iOS 14 technical integration guide.

Initializing the Unity Ads SDK

ViewcController.h

In your ViewController header (.h), import Unity Ads and set the following delegates:

#import <UnityAds/UnityAds.h>
 
@interface ViewController : UIViewController<UnityAdsInitializationDelegate,
UnityAdsLoadDelegate,
UnityAdsShowDelegate>
 
@property (assign, nonatomic) BOOL testMode;

ViewController.m

To initialize the SDK, you must reference your project’s Game ID for the appropriate platform. You can locate the ID in the Monetize Dashboard by selecting Project Settings from the navigation bar (see the Dashboard guide section on Project Settings for details).

In your ViewController implementation (.m), create a [UnityAdsInitializationDelegate] delegate to handle initialization callbacks, and reference it as a parameter in the initialize method. If you initialize with enablePerPlacementLoad set to true, you must load each Ad Unit before showing an ad.

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [UnityAds
         initialize:kDefaultGameId
         testMode:self.testMode
         enablePerPlacementLoad:true
         initializationDelegate:self];
}
 
// Implement initialization callbacks to handle success or failure: 
#pragma mark : UnityAdsInitializationDelegate
- (void)initializationComplete {
    NSLog(@" - UnityAdsInitializationDelegate initializationComplete" );
    // Pre-load an ad when initialization succeeds, so it is ready to show:
    [UnityAds load:@"Interstitial_iOS" loadDelegate:self];
}
 
- (void)initializationFailed:(UnityAdsInitializationError)error withMessage:(NSString *)message {
    NSLog(@" - UnityAdsInitializationDelegate initializationFailed with message: %@", message );
}

// Implement load callbacks to handle success or failure after initialization:
#pragma mark: UnityAdsLoadDelegate
- (void)unityAdsAdLoaded:(NSString *)adUnitId {
    NSLog(@" - UnityAdsLoadDelegate unityAdsAdLoaded %@", adUnitId);
}
 
- (void)unityAdsAdFailedToLoad:(NSString *)adUnitId
                     withError:(UnityAdsLoadError)error
                   withMessage:(NSString *)message {
    NSLog(@" - UnityAdsLoadDelegate unityAdsAdFailedToLoad %@", adUnitId);
}

Important: Initialize the SDK early in your game’s run-time life cycle, before you need to show ads.

Interstitial display ads

Use the show method to show a loaded ad, and a UnityAdsShowDelegate to handle logic for various show events. In this example, a button triggers the ad:

// Implement a button that calls the show method when clicked:
#pragma mark : Buttons
- (IBAction)showInterstitialButton:(UIButton *)sender {
    [UnityAds show:self adUnitId:@"Interstitial_iOS" showDelegate:self];
}

// Implement callbacks for events related to the show method:
#pragma mark: UnityAdsShowDelegate
- (void)unityAdsShowComplete:(NSString *)adUnitId withFinishState:(UnityAdsShowCompletionState)state {
    NSLog(@" - UnityAdsShowDelegate unityAdsShowComplete %@ %ld", adUnitId, state);
}
 
- (void)unityAdsShowFailed:(NSString *)adUnitId withError:(UnityAdsShowError)error withMessage:(NSString *)message {
    NSLog(@" - UnityAdsShowDelegate unityAdsShowFailed %@ %ld", message, error);
    // Optionally execute additional code, such as attempting to load another ad.
}
 
- (void)unityAdsShowStart:(NSString *)adUnitId {
    NSLog(@" - UnityAdsShowDelegate unityAdsShowStart %@", adUnitId);
}
 
- (void)unityAdsShowClick:(NSString *)adUnitId {
    NSLog(@" - UnityAdsShowDelegate unityAdsShowClick %@", adUnitId);
}

Rewarded video ads

Rewarding players for watching ads increases user engagement, resulting in higher revenue. For example, games may reward players with in-game currency, consumables, additional lives, or experience-multipliers. For more information on how to effectively design your rewarded ads, see documentation on Ads best practices.

To reward players for completing a video ad, make sure the Ad Unit ID used in your show method matches the desired Rewarded Ad Unit ID:

- (IBAction)showRewardedAd:(UIButton *)sender {
    [UnityAds show:self adUnitId:@"Rewarded_iOS" showDelegate:self];
}

Then implement your reward functionality in the unityAdsShowAdComplete callback method:

#pragma mark: UnityAdsShowDelegate
- (void)unityAdsShowComplete:(NSString *)adUnitId withFinishState:(UnityAdsShowCompletionState)state {
    NSLog(@" - UnityAdsShowDelegate unityAdsShowComplete %@ %ld", adUnitId, state);
    if ([adUnitId isEqualToString:@"Rewarded_iOS"] && state == kUnityShowCompletionStateCompleted) {
        // Reward the user.
    }
}

Banner ads

Placement configuration

Banner ads require a specific type of dedicated banner Ad Unit or legacy Placement.

app-ads.txt

app-ads.txt is an IAB initiative to combat fraud and create transparency in the advertising ecosystem. Be sure to implement app-ads.txt as described. Otherwise, banner demand may be significantly decreased.

Script implementation

Note: You must initialize Unity Ads before displaying a banner ad.

Add your banner code in the ViewController implementation (.m). The following script sample is an example implementation for displaying two banner ads on the screen. For more information on the classes referenced, see the UADSBannerView API section.

@interface ViewController () <UADSBannerViewDelegate>
​
// This is the Ad Unit or Placement that will display banner ads:
@property (strong) NSString* adUnitId;
// This banner view object will be placed at the top of the screen:
@property (strong, nonatomic) UADSBannerView *topBannerView;
// This banner view object will be placed at the bottom of the screen:
@property (strong, nonatomic) UADSBannerView *bottomBannerView;
​
@end
​
@implementation ViewController
​
- (void)viewDidLoad {
    [super viewDidLoad];
    self.adUnitId = @"banner";
    [UnityAds initialize: @"1234567" delegate: self testMode: YES];
}
​
// Example method for creating and loading the top banner view object: 
- (void)loadTopBanner{
    // Instantiate a banner view object with the Ad Unit ID and size:
    self.topBannerView = [[UADSBannerView alloc] initWithPlacementId: _adUnitId size: CGSizeMake(320, 50)];
    // Set the banner delegate for event callbacks:
    self.topBannerView.delegate = self;
    // Add the banner view object to the view hierarchy:
    [self addBannerViewToTopView:self.topBannerView];
    // Load ad content to the banner view object:
    [_topBannerView load];
}
​
// Example method for creating and loading the bottom banner view object: 
- (void)loadBottomBanner{
    self.bottomBannerView = [[UADSBannerView alloc] initWithPlacementId: _adUnitId size: CGSizeMake(320, 50)];
    self.bottomBannerView.delegate = self;
    [self addBannerViewToBottomView:self.bottomBannerView];
    [_bottomBannerView load];
}
​
// Example method for discarding the top banner view object (e.g. if there's no fill):
- (void)unLoadTopBanner{
    // Remove the banner view object from the view hierarchy:
    [self.topBannerView removeFromSuperview];
    // Set it to nil:
    _topBannerView = nil;
}
​
// Example method for discarding the bottom banner view object:
- (void)unLoadBottomBanner{
    [self.bottomBannerView removeFromSuperview];
    _bottomBannerView = nil;
}
​
​// Example method for placing the top banner view object:
- (void)addBannerViewToTopView:(UIView *)bannerView {
    bannerView.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addSubview:bannerView];
    [self.view addConstraints:@[
                               [NSLayoutConstraint constraintWithItem:bannerView
                                                            attribute:NSLayoutAttributeTop
                                                            relatedBy:NSLayoutRelationEqual
                                                               toItem:self.topLayoutGuide
                                                            attribute:NSLayoutAttributeBottom
                                                           multiplier:1
                                                             constant:0],
                               [NSLayoutConstraint constraintWithItem:bannerView
                                                            attribute:NSLayoutAttributeCenterX
                                                            relatedBy:NSLayoutRelationEqual
                                                               toItem:self.view
                                                            attribute:NSLayoutAttributeCenterX
                                                           multiplier:1
                                                             constant:0]
                               ]];
}

​// Example method for placing the bottom banner view object:
- (void)addBannerViewToBottomView: (UIView *)bannerView {
    bannerView.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addSubview:bannerView];
    [self.view addConstraints:@[
                               [NSLayoutConstraint constraintWithItem:bannerView
                                                            attribute:NSLayoutAttributeBottom
                                                            relatedBy:NSLayoutRelationEqual
                                                               toItem:self.bottomLayoutGuide
                                                            attribute:NSLayoutAttributeTop
                                                           multiplier:1
                                                             constant:0],
                               [NSLayoutConstraint constraintWithItem:bannerView
                                                            attribute:NSLayoutAttributeCenterX
                                                            relatedBy:NSLayoutRelationEqual
                                                               toItem:self.view
                                                            attribute:NSLayoutAttributeCenterX
                                                           multiplier:1
                                                             constant:0]
                               ]];
}

​// Implement the delegate methods:
#pragma mark : UADSBannerViewDelegate

- (void)bannerViewDidLoad:(UADSBannerView *)bannerView {
    // Called when the banner view object finishes loading an ad.
    NSLog(@"Banner loaded for Ad Unit or Placement: %@", bannerView.placementId);
}

- (void)bannerViewDidClick:(UADSBannerView *)bannerView {
    // Called when the banner is clicked.
    NSLog(@"Banner was clicked for Ad Unit or Placement: %@", bannerView.placementId);
}

- (void)bannerViewDidLeaveApplication:(UADSBannerView *)bannerView {
    // Called when the banner links out of the application.
}


- (void)bannerViewDidError:(UADSBannerView *)bannerView error:(UADSBannerError *)error{
    // Called when an error occurs showing the banner view object.
    NSLog(@"Banner encountered an error for Ad Unit or Placement: %@ with error message %@", bannerView.placementId, [error localizedDescription]);
    // Note that the UADSBannerError can indicate no fill (see API documentation).
}
@end

Banner position

You can place the banner view object into your view hierarchy, just like you would any other view. This allows you to customize the position of each banner instance, or display multiple banners.

Testing

Prior to publishing your game, enable test mode by following these steps:

  1. From the Monetize Dashboard, select your Project.
  2. Select Project Settings from the navigation bar.
  3. Scroll down to the Test Mode section, then edit the Apple App Store.
  4. Select the Override client test mode checkbox, then select the Force test mode ON for all devices radio button.

Run your project and test your ads implementation.

Note: You must enable test mode before testing ads integration, to avoid getting flagged for fraud.

⚠️ **GitHub.com Fallback** ⚠️