Knowledge base

Integration guide for iOS (Objective-C)

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.

Note: If you only intend to implement video, interstitial, and banner ads for your monetization strategy, Unity recommends using the UnityAds API for a simpler integration experience. However, if you plan to implement Personalized Placements, you must integrate Unity Ads with the UnityMonetization API. For more information, please see the Integration for Personalized Placements section.

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 Developer Dashboard, and navigate to the Operate tab.
  2. Select Projects from the left navigation bar.
  3. Click the NEW PROJECT button in the top right corner.

Locate your Project’s Game ID by selecting your Project, then selecting Monetization > Platforms from the left navigation bar. Copy the Apple App Store Game ID, because you need it to activate the Unity Ads service in your game.

Creating a Placement

Placements are triggered events within your game that display monetization content. Manage Placements from the Operate tab of the Developer Dashboard by selecting your Project, then selecting Monetization > Placements from the left navigation bar.

Click the ADD PLACEMENT button to bring up the Placement creation prompt. Name your Placement and select its type:

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

Every Unity Ads-enabled project has a (non-rewarded) 'video' and (rewarded) 'rewardedVideo' Placement by default. Feel free to use one of these for your first implementation if they suit your needs, or create your own.

Importing the Unity Ads framework

Download the Unity Ads framework here.

  1. Drag-and-drop the framework into your Unity Project folder, and copy it.
  2. In your ViewController header (.h), import Unity Ads and set the Unity Ads delegate:
#import <UIKit/UIKit.h>
#import <UnityAds/UnityAds.h>

@interface ViewController : UIViewController<UnityAdsDelegate>
@end

Modifying the properties list

Ad network IDs

Games targeting users running iOS 14 or above must implement Unity Ads' network ID in the information property list file (Info.plist):

  1. In the Xcode project navigator, select Info.plist.
  2. Click the add button (+) beside any key in the property list editor to create a new property key.
  3. Enter the key name SKAdNetworkItems.
  4. For the value type, select Array.
  5. Add a dictionary to the array, with the SKAdNetworkIdentifier key and 4DZT52R2T5.skadnetwork Unity Ads network ID string.
  6. Include an additional dictionary to the array for each additional network in the list of available SKAdNetwork IDs (note that Unity will periodically update the list).

For more information on editing the property list, see the Xcode documentation.

The following example shows an array with the dictionaries that represent Unity Ads.

<array>
    <dict>
        <key>SKAdNetworkIdentifier</key>
        <string>4DZT52R2T5.skadnetwork</string>
    </dict>
    <dict>
        <key>SKAdNetworkIdentifier</key>
        <string>bvpn9ufa9b.skadnetwork</string>
    </dict>
</array>

User tracking description

iOS 14 and above requires publishers to obtain permission to track the user's device across applications. Unity recommends implementing a custom permission flow. To provide a message that informs the user why you are requesting permission to use device tracking data:

  1. In the Xcode project navigator, select Info.plist.
  2. Click the add button (+) beside any key in the property list editor to create a new property key.
  3. Enter the key name NSUserTrackingUsageDescription.
  4. Select a string value type.
  5. Enter the app tracking transparency message in the value field. Some examples include:

    Your data will be used to provide you a better and personalized ad experience.

    We try to show ads for apps and products that will be most interesting to you based on the apps you use, the device you are on, and the country you are in.

    We try to show ads for apps and products that will be most interesting to you based on the apps you use.

    Important: Unity does not provide legal advice. Therefore, the information on this page is not a substitute for seeking your own legal counsel to determine the legal requirements of your business and processes, and how to address them.

For more information, see Apple's developer documentation.

Initializing the Unity Ads SDK

To initialize the SDK, you must reference your Project’s Game ID for the appropriate platform. You can locate the ID on the Operate tab of the Developer Dashboard by selecting the Project, then selecting Settings > Project Settings from the left navigation bar (see the Dashboard guide section on Project Settings for details).

In your ViewController implementation (.m), you’ll need to implement the UnityAdsDelegate interface that handles ad callbacks, and reference it as a parameter in the initialize method. Initialize the SDK early in your game’s run-time life cycle, before you need to show ads. For example:

#import "ViewController.h"

@implementation ViewController

// Initialize the SDK:
- (void) viewDidLoad {
    [super viewDidLoad];
    [UnityAds initialize : @"1234567" delegate : self testMode : true];
}

// Implement the ads listener callback methods:
- (void)unityAdsReady:(NSString *)placementId {
    // Perform logic for ads being available to show.
}

- (void)unityAdsDidStart:(NSString *)placementId {
    // Perform logic for a user starting an ad.
}

- (void)unityAdsDidFinish:(NSString *)placementId
withFinishState:(UnityAdsFinishState)state {
    // Perform logic for a user finishing an ad.    
}

- (void)unityAdsDidError:(UnityAdsError)error withMessage:(NSString *)message {
    // Perform logic for a Unity Ads service error.   
}
@end

Note: You must implement each of the callback methods in the listener interface, even if they are empty functions for now. You will populate them with the appropriate logic where needed in the following sections. For more information on each listener callback method, see documentation on the UnityAdsDelegate interface API.

Interstitial display ads

To display a full-screen interstitial ad using the UnityAds API, initialize the SDK and use the show function.

Interstitial ads example

#import "ViewController.h"

@implementation ViewController

- (instancetype)init {
    self = [super init];
    if (self) {
        [UnityAds initialize:@"1234567" delegate:self testMode:YES];
    }
    return self;
}

// Implement a function to display an ad for the specified Placement if available:
- (void)showAd:(NSString *)placementId {
    if ([UnityAds isReady:placementId]) {
        [UnityAds show:self placementId:placementId];
    }
}

// Implement the UnityAdsDelegate methods:

- (void)unityAdsReady:(NSString *)placementId {
    // Implement functionality for an ad being ready to show.
}

- (void)unityAdsDidStart:(NSString *)placementId {
    // Implement functionality for a user starting to watch an ad.
}

- (void)unityAdsDidFinish:(NSString *)placementId
withFinishState:(UnityAdsFinishState)state {
    // Implement functionality for a user finishing an ad.    
}

- (void)unityAdsDidError:(UnityAdsError)error withMessage:(NSString *)message {
    // Implement functionality for a Unity Ads service error occurring.   
}
@end

In this example, you can invoke showAd from anywhere in your game you wish to show an interstitial ad.

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, add logic for the unityAdsDidFinish callback method to check if the user finished the ad and should be rewarded.

Rewarded video example

#import "ViewController.h"

@implementation ViewController

- (instancetype)init {
    self = [super init];
    if (self) {
        [UnityAds initialize:@"1234567" delegate:self testMode:YES];
    }
    return self;
}

// Implement a function to display an ad for the specified Placement:
- (void)showRewardedAd:(NSString *)placementId {
    // If the Placement is rewarded:
    if ([self.placementId isEqualToString:placementId]) {
        // Show an ad if the Placement has content available:
        if ([UnityAds isReady:placementId]) {
            [UnityAds show:self placementId:placementId];
        }
    }
}

// Implement the UnityAdsDelegate methods, filling out unityAdsDidFinish:

- (void)unityAdsReady:(NSString *)placementId {
    // Implement functionality for an ad being ready to show.
}

- (void)unityAdsDidStart:(NSString *)placementId {
    // Implement functionality for a user starting to watch an ad.
}

- (void)unityAdsDidFinish:(NSString *)placementId
withFinishState:(UnityAdsFinishState)state {
    // Conditional logic dependent on whether the player finished the ad:
    if ([self.placementId isEqualToString:placementId]) {
        if (state == kUnityAdsFinishStateCompleted) {
            // Reward the user for watching the ad to completion:
            [self.delegate giveReward:placementId finishState:state];
        } else if (state == kUnityAdsFinishStateSkipped) {
            // Do not reward the user for skipping the ad.
        } else if (state == kUnityAdsFinishStateError) {
            Debug.LogWarning (“The ad did not finish due to an error.);
        }
    }    
}

- (void)unityAdsDidError:(UnityAdsError)error withMessage:(NSString *)message {
    // Implement functionality for a Unity Ads service error occurring.   
}
@end

Placement configuration

Banner ads require a specific type of dedicated banner Placement.

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 Placement that will display banner ads:
@property (strong) NSString* bannerPlacementId;
// 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.bannerPlacementId = @"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 Placement ID and size:
    self.topBannerView = [[UADSBannerView alloc] initWithPlacementId: _bannerPlacementId 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: _bannerPlacementId size: CGSizeMake(320, 50)];
    self.bottomBannerView.delegate = self;
    [self addBannerViewToTopView: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
                                                         r   elatedBy: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 Placement: %@", bannerView.placementId);
}

- (void)bannerViewDidClick:(UADSBannerView *)bannerView {
    // Called when the banner is clicked.
    NSLog(@"Banner was clicked for 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 Placement: %@ with error message %@", bannerView.placementId, [error localizedDescription]);
    // Note that the UADSBannerError can indicate no fill (see API documentation).
}
@end

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 Operate tab of the Developer Dashboard, select your Project.
  2. Select Monetization > Platforms from the left navigation bar.
  3. Select the desired platform, then select the SETTINGS tab.
  4. Scroll down to the TEST MODE section and toggle override client test mode, then select the Force test mode ON 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.

Still need help? Get in touch!
Last updated on 29th Sep 2020