- 
                Notifications
    
You must be signed in to change notification settings  - Fork 43
 
api ios
/*
Title: iOS API reference
Description:
Sort: 5
*/
This article documents API classes for the following namespaces:
For a comprehensive integration guide, click here.
Use this namespace to implement basic ad content, such as rewarded or non-rewarded video, interstitial, or banner ads.
#import <UnityAds/UnityAds.h>
Initializes the Unity Ads service, with a specified Game ID and test mode status.
+ (void)initialize:(NSString *)gameId
    delegate:(nullable id<UnityAdsDelegate>)delegate
    testMode:(BOOL)testMode
    enablePerPlacementLoad:(BOOL)enablePerPlacementLoad;
}  
| Parameter | Data type | Description | 
|---|---|---|
gameId | 
NSString | The Unity Game ID for your Project, located in the developer dashboard. | 
delegate | 
UnityAdsDelegate | 
The delegate for UnityAdsDelegate callbacks. | 
testMode | 
BOOL | Set to YES to enable test mode, and NO to disable it. When in test mode, your game will not receive live ads. | 
enablePerPlacementLoad | 
boolean | When set to true, this parameter allows you to load content for a specific Placement prior to displaying it. Please review the load method documentation before enabling this setting. | 
You can check the initialization status with the following function:
+ (BOOL)isInitialized;
You can check whether the current platform is supported by the SDK with the following function:
+ (BOOL)isSupported;
Loads ad content for a specified Placement, allowing for more accurate fill request reporting that is consistent with the standards of most mediation providers. If you initialized the SDK with enablePerPlacementLoad enabled, you must call load before calling show.
Note: The load API is in closed beta and available upon invite only. If you would like to be considered for the beta, please contact Unity Ads.
+ (void)load:(NSString *)placementId;
Shows content in the specified Placement, if it is ready.
+ (void)show:(UIViewController *)viewController placementId: (NSString *)placementId;
Returns whether an ad is ready to be shown for the specified Placement.
+ (BOOL)isReady:(NSString *)placementId;
| Parameter | Data type | Description | 
|---|---|---|
placementId | 
NSString | The Placement ID, located on the developer dashboard. | 
You can check whether an ad is ready to be shown for the specified Placement by calling:
+ (BOOL)isReady: (NSString *)placementId;
Adds an active listener for UnityAdsDelegate callbacks.
+ (void)addDelegate:(id<UnityAdsDelegate>)delegate;
Allows you to remove an active listener delegate.
+ (void)removeDelegate:(id<UnityAdsDelegate>)delegate;
Controls the amount of logging output from the SDK. Set to true for more robust logging.
+ (void)setDebugMode:(BOOL)enableDebugMode;
You can check the current status for debug logging from the SDK by calling:
+ (BOOL)getDebugMode;
An interface for handling various states of an ad. Implement this listener delegate in your script to define logic for rewarded ads. The interface has the following methods:
@protocol UnityAdsDelegate <NSObject>
- (void)unityAdsReady:(NSString *)placementId;
- (void)unityAdsDidStart:(NSString *)placementId;
- (void)unityAdsDidFinish:(NSString *)placementId
    withFinishState:(UnityAdsFinishState)state;
- (void)unityAdsDidError:(UnityAdsError)error withMessage: (NSString *)message;
@end
Note: Unity recommends implementing all of these methods in your code, even if you don’t use them all.
| Interface method | Description | 
|---|---|
unityAdsReady | 
Handles logic for ad content being ready to display through a specified Placement. | 
unityAdsDidStart | 
Handles logic for the player triggering an ad to play. | 
unityAdsDidFinish | 
Handles logic for an ad finishing. Define conditional behavior for different finish states by accessing the FinishState result from the listener delegate (documented below). For example:- (void)unityAdsDidFinish: (NSString *)placementId  | 
unityAdsDidError | 
Handles logic for ad content failing to display because of an error. | 
The enumerated states of the end-user’s interaction with the ad. The SDK passes this value to the unityAdsDidFinish callback after the ad completes.
typedef NS_ENUM(NSInteger, UnityAdsFinishState)
| Value | Description | 
|---|---|
kUnityAdsFinishStateError | 
Indicates that the ad failed to complete due to a Unity error. | 
kUnityAdsFinishStateSkipped | 
Indicates that the user skipped the ad. | 
kUnityAdsFinishStateCompleted | 
Indicates that the user successfully finished watching the ad. | 
The enumerated states of a Unity Ads Placement.
typedef NS_ENUM(NSInteger, UnityAdsPlacementState)
| Value | Description | 
|---|---|
kUnityAdsPlacementStateReady | 
The Placement is ready to show ads. | 
kUnityAdsPlacementStateNotAvailable | 
The Placement is not available. | 
kUnityAdsPlacementStateDisabled | 
The Placement was disabled. | 
kUnityAdsPlacementStateWaiting | 
The Placement is waiting to be ready. | 
kUnityAdsPlacementStateNoFill | 
The Placement has no advertisements to show. | 
Retrieve the UnityAdsPlacementState value with the following function:
+ (UnityAdsPlacementState)getPlacementState:(NSString *)placementId;
The enumerated causes of a Unity Ads error.
| Value | Description | 
|---|---|
kUnityAdsErrorNotInitialized = 0 | 
The Unity Ads service is currently uninitialized. | 
kUnityAdsErrorInitializedFailed | 
An error occurred in the initialization process. | 
kUnityAdsErrorInvalidArgument | 
Unity Ads initialization failed due to invalid parameters. | 
kUnityAdsErrorVideoPlayerError | 
An error occurred due to the video player failing. | 
kUnityAdsErrorInitSanityCheckFail | 
Initialization of the Unity Ads service failed due to an invalid environment. | 
kUnityAdsErrorAdBlockerDetected | 
An error occurred due to an ad blocker. | 
kUnityAdsErrorFileIoError | 
An error occurred due to inability to read or write a file. | 
kUnityAdsErrorDeviceIdError | 
An error occurred due to a bad device identifier. | 
kUnityAdsErrorShowError | 
An error occurred when attempting to show an ad. | 
kUnityAdsErrorInternalError | 
An internal Unity Ads service error occurred. | 
Use this namespace to implement banner ads.
The basic method for loading banner ad content. You can adjust this function with several parameters, depending on your needs.
| Method | Description | 
|---|---|
+ (void)loadBanner; | 
Loads the banner ad with the default Placement ID. | 
+ (void)loadBanner:(NSString *)placementId; | 
Loads the banner ad with a specific Placement ID (located on the developer dashboard). | 
For example:
- (void)loadBanner {
    if ([UnityAds isReady:self.bannerPlacementId]) {
        [UnityAdsBanner loadBanner:self.bannerPlacementId];
    }
}
Sets the position of the banner ad, using the UnityAdsBannerPosition enum.
+ (void)setBannerPosition:(UnityAdsBannerPosition)bannerPosition;
Destroys the banner ad, removing it from the view hierarchy and hiding it from the player.
+ (void)destroy;
Implement this interface to handle various banner states. The listener delegate includes the following methods:
@protocol UnityAdsBannerDelegate <NSObject>
- (void)unityAdsBannerDidLoad:(NSString *)placementId view: (UIView *)view;
- (void)unityAdsBannerDidUnload:(NSString *)placementId;
- (void)unityAdsBannerDidShow:(NSString *)placementId;
- (void)unityAdsBannerDidClick:(NSString *)placementId;
- (void)unityAdsBannerDidHide:(NSString *)placementId;
- (void)unityAdsBannerDidError:(NSString *)message;
@end
Note: Unity recommends implementing all of these methods in your code, even if you don’t use them all.
| Interface method | Description | 
|---|---|
unityAdsBannerDidLoad | 
Called when the Unity banner finishes loading an ad. The view parameter references the banner that should be inserted into the view hierarchy. For example:- (void)unityAdsBannerDidLoad:(NSString *)placementId view:(UIView *view {
 | 
unityAdsBannerDidUnload | 
Called when ad content is unloaded from the banner, and references to its view should be removed. | 
unityAdsBannerDidShow | 
Called when the Unity banner is shown for the first time and visible to the user. | 
unityAdsBannerDidClick | 
Called when the Unity banner is clicked. | 
unityAdsBannerDidHide | 
Called when the Unity banner is hidden. | 
unityAdsBannerDideError | 
Called when an error occurs showing the banner. | 
You can set or retrieves the assigned UnityAdsBannerDelegate for Unity Ads to send banner callbacks to, using the following methods:
+ (void)setDelegate:(id <UnityAdsBannerDelegate>)delegate;
+ (nullable id <UnityAdsBannerDelegate>)getDelegate;
The enumerated positions you can set as an anchor for banner ads.
typedef NS_ENUM(NSInteger, UnityAdsBannerPosition) {
    kUnityAdsBannerPositionTopLeft,
    kUnityAdsBannerPositionTopCenter,
    kUnityAdsBannerPositionTopRight,
    kUnityAdsBannerPositionBottomLeft,
    kUnityAdsBannerPositionBottomCenter,
    kUnityAdsBannerPositionBottomRight,
    kUnityAdsBannerPositionCenter,
    kUnityAdsBannerPositionNone
};
Use this namespace to implement ads for use with Personalized Placements.
#import <UnityAds/UnityMonetization.h>
Initializes Unity Ads in your game at run time. To avoid errors, initialization should occur early in the game’s run-time lifecycle, preferably at boot. Initialization must occur prior to showing ads.
+ (void)initialize:(NSString *)gameId delegate:(nullable id <UnityMonetizationDelegate>)delegate testMode:(BOOL)testMode;
| Parameter | Description | 
|---|---|
gameID | 
The Game ID for your Project found on the developer dashboard. | 
delegate | 
The listener delegate for UnityMonetizationDelegate callbacks. | 
testMode | 
Indicates whether the game is in test mode. When testMode is true, you will only see test ads. When testMode is false, you will see live ads. It is important to use test mode prior to launching your game, to avoid being flagged for fraud. | 
Checks whether a UMONPlacementContent object is ready for the given Placement. Returns YES if content is ready, and NO if it isn’t.
+ (BOOL)isReady:(NSString *)placementId;
An interface for handling various states of UMONPlacementContent objects. The interface has the following methods:
@protocol UnityMonetizationDelegate <UnityServicesDelegate>
- (void)placementContentReady:(NSString *)placementId
    placementContent:(UMONPlacementContent *)decision;
- (void)placementContentStateDidChange:(NSString *)placementId
    placementContent:(UMONPlacementContent *)placementContent
        previousState:(UnityMonetizationPlacementContentState)previousState
            newState:(UnityMonetizationPlacementContentState)newState;
@end
| Interface method | Description | 
|---|---|
placementContentReady | 
Notifies you that a UMONPlacementContent object is available for a given Placement and is ready to show. | 
placementContentStateDidChange | 
Notifies you when the readied UMONPlacementContent object’s status has changed due to a refresh. | 
Example UnityMonetizationDelegate implementation:
@interface MyMonetizationDelegate <UnityMonetizationDelegate>
@end
@implementation MyMonetizationDelegate
- (void)placementContentReady:(NSString *)placementId
    placementContent:(UMONPlacementContent *)placementContent {
    if ([placementId isEqualToString:@"video"]) {
        self.interstitial = placementContent;
    } else if ([placementId isEqualToString:@"rewardedVideo"]) {
        self.rewardedVideo = placementContent;
    }
}
- (void)placementContentStateDidChange:(NSString *)placementId
    placementContent:(UMONPlacementContent *)decision
        previousState:(UnityMonetizationPlacementContentState)previousState
            newState:(UnityMonetizationPlacementContentState)newState {
    if (newState != kPlacementContentStateReady) {
        // Disable showing ads because content isn't ready anymore
    }
}
@end
Implement this delegate to provide the unityAdsDidFinish callback method for a video ad’s UnityAdsFinishState. The interface has the following methods:
@protocol UMONShowAdDelegate <NSObject>
- (void)unityAdsDidStart:(NSString*)placementId;
- (void)unityAdsDidFinish:(NSString*)placementId withFinishState:(UnityAdsFinishState)finishState;
@end
| Interface method | Description | 
|---|---|
unityAdsDidStart | 
Handles logic for the player triggering an ad to play. | 
unityAdsDidFinish | 
Implement this method to provide logic for handling whether the ad was completed, skipped, or errored out, depending on the finish state. | 
A class representing monetization content that your Placement can display.
Associated methods:
| Method | Description | 
|---|---|
- (BOOL)isReady | 
Returns YES if the UMONPlacementContent object is ready to display, and NO if it isn’t. | 
- (NSString)getType; | 
Returns the type of UMONPlacementContent available to display. The following string values are valid:
  | 
Extends the UMONPlacementContent class with functionality to support rewarded content.
Associated methods:
| Method | Description | 
|---|---|
- (BOOL)isRewarded | 
Returns YES if the UMONPlacementContent is rewarded, and NO if it isn’t. | 
Extends the UMONRewardablePlacementContent class with functionality to support video ad content.
| Method | Description | 
|---|---|
- (void)show:(UIViewController *)viewController withDelegate:(id <UMONShowAdDelegate>)delegate; | 
Displays the available UMONShowAdPlacementContent. Implement a UMONShowAdDelegate delegate to define how this function responds to each ad finish state. | 
Extends the UMONShowAdPlacementContent class, providing functionality for IAP Promo content. For more information, see documentation on Native Promos.
An enum representing the final state of an ad when finished. Use it to handle reward cases.
| Value | Description | 
|---|---|
kUnityAdsFinishStateCompleted | 
The player viewed the ad in its entirety. | 
kUnityAdsFinishStateSkipped | 
The player skipped the ad before it played in its entirety. | 
kUnityAdsFinishStateError | 
The ad failed to load. | 
Example unityAdsDidFinish implementation:
- (void)unityAdsDidFinish:(NSString *)placementId withFinishState:(UnityAdsFinishState)finishState {
    NSLog (@"UnityAds FINISH: %@", placementId);
    if (finishState == kUnityAdsFinishStateCompleted && [placementId isEqualToString: @"rewardedVideo"]) {
        // Reward the player
        ((UMONShowAdPlacementContent *) self.rewardedContent).rewarded = YES;
        NSLog (@"Reward the player");
    }
}
This class manages purchasing adapters, which are interfaces for the SDK to retrieve the information it needs from your custom IAP implementation.
@interface USRVUnityPurchasing: NSObject
+ (void)setDelegate:(id<USRVUnityPurchasingDelegate>)delegate;
+ (nullable id<USRVUnityPurchasingDelegate>)getDelegate;
@end
Your custom game logic for handling a successful transaction, used in a USVRUnityPurchasingDelegate's purchaseProduct method.
Your custom game logic for handling a failed transaction. The function takes a UPURTransactionDetails object. In the example below, a failed transaction calls UnityPurchasingTransactionErrorHandler, which returns a UPURTransactionError enum.
An interface for implementing a custom purchasing solution that's compatible with IAP Promo. The interface has the following methods:
typedef void (^UnityPurchasingLoadProductsCompletionHandler) (NSArray<UPURProduct*>*);
typedef void (^UnityPurchasingTransactionCompletionHandler) (UPURTransactionDetails*);
typedef void (^UnityPurchasingTransactionErrorHandler) (UPURTransactionError, NSException*);
@protocol USRVUnityPurchasingDelegate
- (void)loadProducts:(UnityPurchasingLoadProductsCompletionHandler)completionHandler;
- (void)purchaseProduct:(NSString *)productId 
    completionHandler:(UnityPurchasingTransactionCompletionHandler)completionHandler
        errorHandler:(UnityPurchasingTransactionErrorHandler)errorHandler
            userInfo:(nullable NSDictionary *)extras;
@end
| Interface method | Description | 
|---|---|
loadProducts | 
The SDK calls this to retrieve the list of available Products. It uses the UnityPurchasingProductsCompletionHandler interface, which takes a UPURProduct object to register your Products (example below). | 
purchaseProduct | 
The SDK calls this when a user clicks the buy button for a promotional asset. Unity passes the purchased Product’s ID to your in-app purchasing system. The function uses the UnityPurchasingTransactionCompletionHandler and UnityPurchasingTransactionErrorHandler functions to handle the purchase’s success or failure according to your implementation. | 
Example of an implemented loadProducts function:
- (void)loadProducts:(UnityPurchasingLoadProductsCompletionHandler)completionHandler {
    completionHandler (@[[UPURProduct build:^(UPURProductBuilder *builder){
        builder.productId = @"100BronzeCoins";
        builder.localizedTitle = @"100 Bronze Coins";
        builder.localizedPriceString = @"$1.99";
        builder.localizedPrice = [NSDecimalNumber decimalNumberWithString:@"1.99"];
        builder.isoCurrencyCode = @"USD";
        builder.localizedDescription = @"Awesome Bronze Coins available for a low price!";
        builder.productType = @"Consumable";
    }]]);
}
Example purchaseProduct implementation:
- (void)purchaseProduct:(NSString *)productId completionHandler:(UnityPurchasingTransactionCompletionHandler)completionHandler errorHandler:(UnityPurchasingTransactionErrorHandler)errorHandler userInfo:(nullable NSDictionary *)extras {
    thirdPartyPurchasing.purchase (productId); // Generic developer purchasing function
   
    // If purchase succeeds:
    completionHandler ([UPURTransactionDetails build: ^(UPURTransactionDetailsBuilder *builder) {
        builder.productId = productId;
        builder.transactionId = thirdPartyPurchasing.transactionId;
        builder.currency = @"USD";
        builder.price = [NSDecimalNumber decimalNumberWithString: @"1.99"];
        builder.receipt = @"{\n\"data\": \"{\\\"Store\\\":\\\"fake\\\",\\\"TransactionID\\\":\\\"ce7bb1ca-bd34-4ffb-bdee-83d2784336d8\\\",\\\"Payload\\\":\\\"{ \\\\\\\"this\\\\\\\": \\\\\\\"is a fake receipt\\\\\\\" }\\\"}\"\n}";
    }]);
    
    // If purchase fails:
    errorHandler (kUPURTransactionErrorNetworkError, nil);
}
@end
This interface provides access methods for handling user interaction with promotional assets. Use these methods to pass in your custom assets and define expected behavior. Pass a UMONPromoAdPlacementContent object through the initWithPromo function to create a new adapter. For example:
`self.nativePromoAdapter = [[UMONNativePromoAdapter alloc] initWithPromo: placementContent];`
| Interface method | Description | 
|---|---|
- (void)promoDidShow: (UMONNativePromoShowType)showType; | 
The SDK calls this function when the Promo displays. It should include your custom method for displaying promotional assets. You can pass a UMONNativePromoShowType enum value to reference the preview type of your Promo asset. | 
- (void)promoDidClose; | 
The SDK calls this function when the player dismisses the Promo offer. | 
- (void)promoDidClick; | 
The SDK calls this function when the player clicks the button to purchase the Product. It should initiate the purchase flow. | 
Example UMONNativePromoAdapter implementation:
@interface ViewController: UIViewController <USRVUnityPurchasingDelegate>
- (void)showPromo:(UMONPromoAdPlacementContent *)placementContent {
    self.nativePromoAdapter = [[UMONNativePromoAdapter alloc] initWithPromo:placementContent];
    UMONPromoMetaData *metaData = placementContent.metadata;
    UPURProduct *product = metaData.premiumProduct;
    NSString *price = (product == nil || product.localizedPriceString == nil) ? @"$0.99": product.localizedPriceString;
    
    self.nativePromoView.hidden = NO;
    NSString *title = [NSString stringWithFormat: @"Buy for only %@", price];
    [self.purchaseButton setTitle: title forState: UIControlStateNormal];
    [self.nativePromoAdapter promoDidShow];    
}
// If the player clicked the purchase button:
(IBAction)purchaseButtonTapped:(id)sender {
    [self.nativePromoAdapter promoDidClick];
    [self.nativePromoAdapter promoDidClose];
    self.nativePromoView.hidden = YES;
}
// If the player closed the promotional asset:
- (IBAction)promoCloseButtonTapped:(id)sender {
    self.nativePromoView.hidden = YES;
    [self.nativePromoAdapter promoDidClose];
}
An IAP product converted into an object that the SDK can use for optimizing monetization.
Set the following fields on the @interface UPURProductBuilder:NSObject builder, then call + (instancetype)build:(void (^) (UPURProductBuilder *))buildBlock to construct the final object:
| Builder method | Param type | Description | 
|---|---|---|
productId | 
NSString | 
An internal reference ID for the Product. | 
localizedTitle | 
NSString | 
A consumer-facing name for the Product, for store UI purposes. | 
localizedPriceString | 
NSString | 
A consumer-facing price string, including the currency sign, for store UI purposes. | 
localizedPrice | 
NSDecimalNumber | 
The internal system value for the Product’s price. | 
isoCurrencyCode | 
NSString | 
The ISO code for the Product’s localized currency. | 
localizedDescription | 
NSString | 
A consumer-facing Product description, for store UI purposes. | 
productType | 
NSString | 
Unity supports "Consumable", "Non-consumable", and "Subscription" Product types. | 
For more details on Product properties, see documentation on defining Products.
An IAP transaction receipt converted into an object that the SDK can use for optimizing monetization.
| Property | Type | Description | 
|---|---|---|
productId | 
NSString | An internal reference ID for the Product. | 
transactionId | 
NSString | An internal reference ID for the transaction. | 
receipt | 
NSString | The JSON fields from the appStoreReceiptURL detailing the transaction. Encode the receipt as a JSON object containing Store, TransactionID, and Payload. | 
price | 
NSDecimalNumber | The internal system value for the Product’s price. | 
currency | 
NSString | The ISO code for the Product’s localized currency. | 
For more details, see Apple’s documentation on In-App Purchase receipt fields.
An enum indicating the reason a transaction failed.
typedef NS_ENUM (NSInteger, UPURTransactionError) {
    kUPURTransactionErrorNotSupported,
    kUPURTransactionErrorItemUnavailable,
    kUPURTransactionErrorUserCancelled,
    kUPURTransactionErrorNetworkError,
    kUPURTransactionErrorServerError,
    kUPURTransactionErrorUnknownError
};
NSString *NSStringFromUPURTransactionError (UPURTransactionError);
An enum indicating which store the transaction came from.
typedef NS_ENUM (NSInteger, UPURStore) {
    kUPURStoreNotSpecified,
    kUPURStoreGooglePlay,
    kUPURStoreAmazonAppStore,
    kUPURStoreCloudMoolah,
    kUPURStoreSamsungApps,
    kUPURStoreXiaomiMiPay,
    kUPURStoreMacAppStore,
    kUPURStoreAppleAppStore,
    kUPURStoreWinRT,
    kUPURStoreTizenStore,
    kUPURStoreFacebookStore
};
NSString *NSStringFromUPURAppStore(UPURStore);
The enumerated display types of a Native Promo asset.
| Value | Description | 
|---|---|
"FULL" | 
Indicates a full promotional view. | 
"PREVIEW" | 
Indicates a minimized view that can expand to display the full Promo. |