NextGen SDK | iOS Integration

Integration Guide for Publishers with Smaato as a Primary Ad Server

(iOS SDK version 21.6.0)

 

Integrate the NextGen SDK

1.) First, configure your SPX account: https://spx.smaato.com/

2.) Create and save the Xcode “Single View” project. Name it as “MyTarget“. Then close the Xcode.

3.) Next, create a file with the name “Podfile” in the project directory with one of the following snippets or their reasonable combination. With the modular structure of Smaato’s NextGen SDK, you can select different integration options. The following are configuration examples for your project Podfile:

All supported Ad Formats (full Smaato SDK):

pod 'smaato-ios-sdk'

Banner Ads (with Rich Media support)

pod 'smaato-ios-sdk/Banner'

Interstitial Ads (with Rich Media & Video support)

pod 'smaato-ios-sdk/Interstitial'

Rewarded Video Ads

pod 'smaato-ios-sdk/RewardedAds'

Native Ads

pod 'smaato-ios-sdk/Native'


4.)
Open Terminal then go to the project directory.

cd {PATH_TO_PROJECT_DIR}


5.)
Install the pods.

pod install


6.)
The “{PROJECT_NAME}.xcworkspace” file should appear in the project folder. You will then need to open the “{PROJECT_NAME}.xcworkspace” in Xcode.

 

Initialize the NextGen SDK

In the “AppDelegate.mimport SmaatoSDKCore module and configure SDK in “application:didFinishLaunchingWithOptions:

Swift
Objective-C
Swift
// AppDelegate.swift
import UIKit
import SmaatoSDKCore
 
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
     
    var window: UIWindow?
     
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // initialize SDK!        
        guard let config = SMAConfiguration(publisherId: "SMAATO_PUBLISHER_ID") else {
              fatalError("SDK config is nil!")
        }
		// allow HTTPS traffic only
        config.httpsOnly = true 
		// log errors only
        config.logLevel = .error
		// ads content restriction based on age
		config.maxAdContentRating = .undefined
         
        SmaatoSDK.initSDK(withConfig:config)
		// allow the Smaato SDK to automatically get the user's location and put it inside the ad request
        SmaatoSDK.gpsEnabled = true  
 
        // optional, specific configuration        
        SmaatoSDK.userGender = .male // usually set after user logs in
        SmaatoSDK.userAge = 40 // usually set after user logs in
        SmaatoSDK.userSearchQuery = "bitcoin, lamborghini, san+francisco"
         
        return true
    }
}

Objective-C
// AppDelegate.m
#import "AppDelegate.h"
@import SmaatoSDKCore;
 
@implementation AppDelegate
 
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {   
    // initialize SDK first!    
    SMAConfiguration *config = [[SMAConfiguration alloc] initWithPublisherId:@"SMAATO_PUBLISHER_ID"];
	// allow HTTPS traffic only
    config.httpsOnly = YES;                 
	// log errors only
    config.logLevel = kSMALogLevelError;    
	// ads content restriction based on age
	config.maxAdContentRating = kSMAMaxAdContentRatingUndefined;
	[SmaatoSDK initSDKWithConfig:config];
	// allow the Smaato SDK to automatically get the user's location and put it inside the ad request
    SmaatoSDK.gpsEnabled = YES;
     
    // optional configuration    
    SmaatoSDK.userGender = kSMAGenderFemale; // usually set after user logs in
    SmaatoSDK.userAge = @30; // usually set after user logs in
    SmaatoSDK.userSearchQuery = @"yoga, vegan, san+francisco";
     
    return YES;
}

Important Note: Starting from NextGen SDK version 21.2.1, the new GPSEnabled flag allows the SDK to automatically get the user’s location when permission is given by the user. By default, this flag is set to off and the user location will not be provided in the ad request. To enable this the GPSEnabled flag must be set to yes (for objective-c) or true (for swift).

 

Important Details About GDPR

The General Data Protection Regulation (GDPR) was created to provide European users with greater transparency and control over their personal information. As a publisher, you should integrate a Consent Management Platform (CMP) and request for user, vendor, and purpose consents as outlined in IAB Europe’s IAB Tech Lab – CMP API v2. You can find an example implementation of a web-based CMP and the corresponding native wrappers here in the IAB’s GDPR-Transparency-and-Consent-Framework.

You can also make your own custom CMP. The collected end-user consent information needs to be stored in NSUserDefaults using the following keys:

Transparency and Consent Framework v2:

Key Type Description
IABTCF_gdprApplies NSNumber

1 = Subject to GDPR
0 = Not subject to GDPR
-1 or unset = Undetermined (default before initialization)

IABTCF_TCString NSString

Base64-encoded consent string as defined in IAB Tech Lab – Consent string and vendor list formats v2

Sample of GDPR Saving in NSUserDefaults

Swift
Objective-C
Swift
// User is not subject to GDPR
UserDefaults.standard.set("0", forKey: "IABConsent_SubjectToGDPR")
// Use this example above to set values for the rest of the GDPR keys

Objective-C
// User is not subject to GDPR
[[NSUserDefaults standardUserDefaults] setObject:@"0" forKey:@"IABConsent_SubjectToGDPR"];
// Use this example above to set values for the rest of the GDPR keys

 

Important Details About CCPA

The California Consumer Privacy Act (CCPA) was created to provide California consumers with greater transparency and control over their personal information.

For more information about the CCPA regulation, please check out the Smaato FAQ. You can also review the IAB’s U.S. Privacy String documentation.

For Publishers with California-Based Users

As a publisher, you need to make sure to request consent from California-based users (to give or refuse consent / to opt-out or opt-in ) about private data transfer. This answer should be saved in NSUserDefaults with key “IABUSPrivacy_String” in the US Privacy String format (CCPA Opt-Out Storage Format).

Sample of CCPA Saving in NSUserDefaults

Swift
Objective-C
Swift
// save the user's consent
private func saveCCPA(usPrivacy string: String?) {
    guard let usString = string else {
        return
    }
    UserDefaults.standard.set(usString, forKey: "IABUSPrivacy_String"
}
// call this function like this:
// saveCCPA(string: "1YNN")

Objective-C
// save the user's consent
- (void)saveCCPAUsPrivacyString:(NSString *)usString
{
    if (usString.length > 0) {
        [NSUserDefaults.standardUserDefaults setObject:usString 
         forKey:@"IABUSPrivacy_String"];
    }
}
// call this function like this:
// [saveCCPAUsPrivacyString usString:@"1YNN"]; 

NextGen SDK reads that value by key “IABUSPrivacy_String” if it exists and uses it as an optional parameter for all ad requests.

 

 

Ads for Testing Purposes

Adspace ID Type Description
130626424 Rich Media Banner / Med-rect / Leaderboard / Skyscraper
130635694 Static Image Banner / Med-rect / Leaderboard / Skyscraper
130635706 MRAID Banner / Med-rect / Leaderboard / Skyscraper
130626426 Rich Media / Video Interstitial (Video with an end-card + Rich Media Interstitial for 320×480, 480×320, 1024×768 & 768×1024)
130626427 Video Skippable Video
130626428 Rewarded Rewarded Video
130635048 Rewarded Rewarded Video without an end-card
130783664 Native Native with static image main creative

 

Steps to Integrate the Banner

1.) Add SMABannerView to ViewController in Interface Builder.

2.) Layout BannerView so that it takes enough space to display the banner of desired size (i.e. XXLarge takes 320×50 pt).

3.) In the Interface Builder, link the SMABannerView with ViewController via IBOutlet and adopt ViewController to the SMABannerViewDelegate protocol. Then Implement the required SMABannerViewDelegate methods, setup the BannerView, and load the banner.

Swift
Objective-C
Swift
// ViewController.swift
import UIKit
import SmaatoSDKBanner
 
class ViewController: UIViewController { 
	// get the Smaato banner view from the interface
    @IBOutlet weak var bannerView: SMABannerView!
     
    override func viewDidLoad() {
        super.viewDidLoad()
     		 // (optional) set the desired auto-reload time interval
    	   bannerView.autoreloadInterval = .veryShort 
		      // (required) set the delegate
    	   bannerView.delegate = self
		      // load the banner, with desired size
    	   bannerView.load(withAdSpaceId: "SMAATO_ADSPACE_ID", adSize: .xxLarge_320x50)
    }
}
 
extension ViewController: SMABannerViewDelegate {
   // return presenting view controller to display Ad contents modally, e.g. in internal WebBrowser
   func presentingViewController(for bannerView: SMABannerView) -> UIViewController {
        return self
   }
   
   // check if banner loaded successfully
   func bannerViewDidLoad(_ bannerView: SMABannerView) {
        print("Banner has loaded successfully!")
   }
    
   // check if banner failed to load
   func bannerView(_ bannerView: SMABannerView, didFailWithError error: Error) {
        print("Banner failed to load with error: \(error.localizedDescription)")
   }
 
   // notification callback: ads TTL has expired
   func bannerViewDidTTLExpire(_ bannerView: SMABannerView) {
        print("Banner TTL has expired. You should load new one")
   }
}

Objective-C
// ViewController.m
#import "ViewController.h"
@import SmaatoSDKBanner;
 
// declare the ViewController to conform the SMABannerViewDelegate protocol
 
@interface ViewController () 
	// get the Smaato banner view from the interface
 @property (nonatomic, weak) IBOutlet SMABannerView *bannerView;
@end
 
@implementation ViewController
 
 - (void)viewDidLoad {
    [super viewDidLoad];
		// (optional) set the desired auto-reload time interval
    	self.bannerView.autoreloadInterval = kSMABannerAutoreloadIntervalVeryShort; 
		// (required) set the delegate
    	self.bannerView.delegate = self;     
		// load the banner, with desired size
    	[self.bannerView loadWithAdSpaceId:@"SMAATO_ADSPACE_ID" adSize:kSMABannerAdSizeXXLarge_320x50];
}

#pragma mark - 
 
// return presenting view controller to display Ad contents modally, e.g. in internal WebBrowser
- (UIViewController *)presentingViewControllerForBannerView:(SMABannerView *)bannerView {
    return self;
}

// check if banner has loaded successfully
- (void)bannerViewDidLoad:(SMABannerView *)bannerView {
   NSLog(@"Banner has loaded successfully!");
}

// check if banner failed to load
- (void)didFailWithError:(SMABannerView *)bannerView :(Error *)error {
   NSLog(@"Banner failed to load with error: \(error.localizedDescription)");
}
 
// notification callback: ads TTL has expired
- (void)bannerViewDidTTLExpire:(SMABannerView *)bannerView {
    NSLog(@"Banner TTL has expired. You should load new one.");
}

@end

4.) Build and run the app in the Simulator. The banner should then appear on your screen.

 

Steps to Integrate a Native Ad

The main advantage of integrating Native Ads is the ability to fully control the rendering and appearance of ads on-screen. Other types of ads (Banners, Interstitials, and Rewarded Video) are hardcoded and presented on the screen by the NextGen SDK. With Native Ads, you need to supply different UI components to the SDK to perform the final rendering of an ad. However, Smaato recommends that all UI components be added to a dedicated UIView container to handle the clicks by the SDK. Only when the container is registered with the SDK will an ad be visible with clicks enabled and impression and click beacons called.

Native ads might be presented (rendered) on the screen in two different ways:

  • Manual rendering. This means you fetch a native ad’s raw data from the SMANativeAdAssets assets object and render it into your standard or custom UIKit views (i.e. UILabel, UIImageView, etc.). All views with rendered native ads must be placed on the same known UI view container. You handle downloading the ad creatives like the main images and icon, using a framework like Alamofire.
  • Auto rendering. This means you create a special UIView subclass that conforms to and implements the SMANativeView protocol. This protocol defines the UIKit views’ properties and their naming to allow the NextGen SDK to look for the appropriate UI controls for a given type of native ads asset, and displays it directly. The amount of adopted controls from the SMANativeView and their sizes/placements do not matter and depend on your UI/UX preferences. The NextGen SDK handles downloading the ad creatives itself.

1.) Design a Custom UIView and/or Related Class for Native Ads Presentation

If manual rendering is chosen:

Swift
Objective-C
Swift
import UIKit
import SmaatoSDKCore
import SmaatoSDKNative
 
class NativeAdCustomView: UIView {
    @IBOutlet weak var titleTextLabel: UILabel!
    @IBOutlet weak var mainTextLabel: UILabel!
    @IBOutlet weak var ctaLabel: UILabel!
    @IBOutlet weak var sponsoredLabel: UILabel!
    @IBOutlet weak var mainImageView: UIImageView!
    @IBOutlet weak var iconImageView: UIImageView!
}

Objective-C
// NativeAdCustomView.m
#import "NativeAdCustomView.h"
@import SmaatoSDKCore;
@import SmaatoSDKNative;

// make a native ad custom view that is of type UIView
@interface NativeAdCustomView()

@property (weak, nonatomic) UILabel *titleTextLabel;
@property (weak, nonatomic) UILabel *mainTextLabel;
@property (weak, nonatomic) UILabel *ctaLabel;
@property (weak, nonatomic) UILabel *sponsoredLabel;
@property (weak, nonatomic) UIImageView *mainImageView;
@property (weak, nonatomic) UIImageView *iconImageView;

@end

If auto rendering is chosen:

Swift
Objective-C
Swift
import UIKit
import SmaatoSDKCore
import SmaatoSDKNative
 
class NativeAdSmaatoView: UIView, SMANativeView {
    @IBOutlet weak var smaSponsoredLabel: UILabel!
    @IBOutlet weak var smaMainTextLabel: UILabel!
    @IBOutlet weak var smaTitleLabel: UILabel!
    @IBOutlet weak var smaIconView: UIView!
    @IBOutlet weak var smaMediaView: UIView!
    @IBOutlet weak var smaCTALabel: UILabel!
    @IBOutlet weak var smaPrivacyView: UIView!
}

Objective-C
// NativeAdSmaatoView.m
#import "NativeAdSmaatoView.h"
@import SmaatoSDKCore;
@import SmaatoSDKNative;

// make a native ad custom view that is of type UIView and of SMANativeView
@interface NativeAdSmaatoView()

@property (weak, nonatomic) UILabel *smaSponsoredLabel;
@property (weak, nonatomic) UILabel *smaMainTextLabel;
@property (weak, nonatomic) UILabel *smaTitleLabel;
@property (weak, nonatomic) UIView *smaIconView;
@property (weak, nonatomic) UIView *smaMediaView;
@property (weak, nonatomic) UILabel *smaCTALabel;
@property (weak, nonatomic) UIView *smaPrivacyView;

@end

2.) Adopt the ViewController Presenting the Native Ad to the SMANativeAdDelegate Protocol

Implement the required SMANativeAdDelegate methods. Instantiate a new native ad and set the delegate. Use a SMANativeAdRequest object to set loading options:

allowMultipleImages – indicates your intention to display several main images (up to 3). Defaults to NO (Obj-C) / false (Swift).

returnUrlsForImageAssets – Indicates whether the icon and main image creatives should be downloaded. If set to NO (Obj-C) or false (Swift), the NextGen SDK downloads required creatives and provides all of them as UIImage objects. Defaults to YES (Obj-C) or true (Swift), and image creatives are not downloaded by NextGen SDK. It is your responsibility to fetch the creative URLs.

Make an ad request with the loadWithAdRequest: method and listen to the delegate callbacks. Render your native ads based on the SMANativeAdRenderer result parameter while in manual or auto rendering mode. Then register the native ad container view for impression tracking and user interaction handling once the ad is loaded. Two ways of rendering depending on whether you chose manual or auto rendering are listed below in the didLoadWithAdRenderer method (choose one):

Swift
Objective-C
Swift
import UIKit
import SmaatoSDKCore
import SmaatoSDKNative
 
class ViewController: UIViewController {
    private var nativeAd: SMANativeAd?
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        guard let adRequest = SMANativeAdRequest(adSpaceId:"SMAATO_ADSPACE_ID_HERE") else {
            return
        }
        nativeAd = SMANativeAd()
        adRequest.allowMultipleImages = false
        adRequest.returnUrlsForImageAssets = false
        nativeAd.delegate = self   // (required) set the delegate
        nativeAd.load(with: adRequest)
    }
}
 
extension ViewController: SMANativeAdDelegate {

    // Sent when the native ad loads a creative successfully
    func nativeAd(_ nativeAd: SMANativeAd, didLoadWith renderer: SMANativeAdRenderer) {
        
        // -----> IMPORTANT: EXECUTE THE BELOW CODE IF YOU CHOSE MANUAL RENDERING: <-----
        
        print("\(nativeAd) loaded successfully")   
        //Create new instance of your custom designed native ad view: load from .xib or create programmatically
        guard let adView = NativeAdCustomView.instantiateFromNib() else {
            return nil
        }
 
        //Register ad view for impression tracking and user clicks handling
        renderer.registerView(forImpression: adView)
        renderer.registerViews(forClickAction: [adView.titleTextLabel,  adView.mainTextLabel, adView.mainImageView, adView.iconImageView, adView.ctaLabel])
     
        //Explicit rendering of native ad raw data into UI controls of given ad view
        let assets = renderer.nativeAssets
        adView.titleTextLabel.text = assets.title
        adView.mainTextLabel.text = assets.mainText
        adView.sponsoredLabel.text = assets.sponsored
        //You should care yourself about image creatives downloading. NextGen SDK provides helper class for this purpose, but you are able to do it through your lovely Alamofire
        SMANativeImageLoader.loadImage(with: assets.iconURL) { [weak nativeView = adView] (image, error) in
            nativeView?.iconImageView.image = image
        }
        SMANativeImageLoader.loadImage(with: assets.imageURLs?.first) {  [weak nativeView = adView] (image, error) in
           nativeView?.mainImageView.image = image
        }
 
        //Add ad view on the screen
        self.view.addSubview(adView)
        
        // -----> IMPORTANT: EXECUTE THE BELOW CODE IF YOU CHOSE AUTO RENDERING: <-----
        
        print("\(nativeAd) loaded successfully")   
        //Create new instance of your custom designed native ad view that conforms  protocol: load from .xib or create programmatically
        guard let adView = NativeAdSmaatoView.instantiateFromNib() else {
            return nil
        }
 
        //Download all required image resources and render them in asynchronous mode
        renderer.renderAd(in: adView) {[weak self, weak adRenderer = renderer] (success, error) in
        guard let this = self,
              let renderer = adRenderer else {
               print("No destination for ad")
               return
        }    
        if (success) {
            print("Native ad has been rendered")
            //Register ad view for impression tracking and user clicks handling
            renderer.registerView(forImpression: adView)
            renderer.registerViews(forClickAction: [adView.smaTitleLabel!, adView.smaMainTextLabel!, adView.smaIconView!, adView.smaMediaView!, adView.smaCTALabel!])
            //Add ad view on the screen
            this.view.addSubview(adView)
        } else {
            print("Native ad rendering error \(error?.localizedDescription ?? "")")
        }
      }
    }
 
    // Sent when the native ad fails to load an ad successfully
    func nativeAd(_ nativeAd: SMANativeAd, didFailWithError error: Error) {
        print("\(nativeAd) failed with error: \(error)")
    }
    
    // A view controller that will be used to present modal view controllers
    func presentingViewController(for nativeAd: SMANativeAd) -> UIViewController {
        return self
    }
 
    // Sent when TTL has expired, based on the timestamp from the ad header
    func nativeAdDidTTLExpire(_ nativeAd: SMANativeAd) {
        print("\(nativeAd) TTL has expired. Please load a new one. Tip: show Native before expiration for the best fill rate (you have about 5 minutes after loading completion).")
    }
}

Objective-C
// ViewController.m
#import "ViewController.h"
@import SmaatoSDKCore;
@import SmaatoSDKNative;
 
// declare the ViewController to conform to the SMANativeAdDelegate protocol
@interface ViewController () 
@property (nonatomic, strong) SMANativeAd *nativeAd;
@end
 
@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.nativeAd = [SMANativeAd new];
    SMANativeAdRequest *adRequest = [[SMANativeAdRequest alloc] initWithAdSpaceId:@"SMAATO_ADSPACE_ID_HERE"];
    adRequest.allowMultipleImages = NO;
    adRequest.returnUrlsForImageAssets = NO;
    self.nativeAd.delegate = self; // (required) set the delegate
    [self.nativeAd loadWithAdRequest:adRequest];
}

//Sent when the native ad loads a creative successfully.
- (void)nativeAd:(SMANativeAd *)nativeAd didLoadWithAdRenderer:(SMANativeAdRenderer *)renderer {

    // -----> IMPORTANT: EXECUTE THE BELOW CODE IF YOU CHOSE MANUAL RENDERING: <-----

    NSLog(@"Native loaded successfully");
    //Create new instance of your custom designed native ad view: load from .xib or create programmatically
    NativeAdCustomView *adView = [NativeAdCustomView demo_instantiateFromNib];
    if (!adView) {
        return nil;
    }
     
    //Register ad view for impression tracking and user clicks handling
    [renderer registerViewForImpression:adView];
    [renderer registerViewsForClickAction:@[adView.titleTextLabel, adView.mainTextLabel, adView.mainImageView, adView.iconImageView, adView.ctaLabel]];
 
    //Explicit rendering of native ad raw data into UI controls of given ad view
    SMANativeAdAssets *assets = renderer.nativeAssets;
    adView.titleTextLabel.text = assets.title;
    adView.mainTextLabel.text = assets.mainText;
    adView.sponsoredLabel.text = assets.sponsored;
    //You should care yourself about image creatives downloading. NextGen SDK provides helper class for this purpose, but you are able to do it through your lovely AFNetworking
    __typeof__(adView) __weak wView = adView;
    [SMANativeImageLoader loadImageWithURL:assets.iconURL completion:^(UIImage *image, NSError *error) {
        __typeof__(adView) sView = wView;
        sView.iconImageView.image = image;
    }];
    [SMANativeImageLoader loadImageWithURL:assets.imageURLs.firstObject completion:^(UIImage *image, NSError * error) {
        __typeof__(adView) sView = wView;
        sView.mainImageView.image = image;
    }];
 
    //Add ad view on the screen
    [self.view addSubview:adView];
    
    
    // -----> IMPORTANT: EXECUTE THE BELOW CODE IF YOU CHOSE AUTO RENDERING: <-----
    
    NSLog(@"Native loaded successfully");
    //Create new instance of your custom designed native ad view that conforms  protocol: load from .xib or create programmatically
    NativeAdSmaatoView *adView = [NativeAdSmaatoView demo_instantiateFromNib];
    if (!adView || ! [adView conformsToProtocol:@protocol(SMANativeView)]) {
        return nil;
    }
 
    //Download all required image resources and render them in asynchronous mode
    __typeof__(self) __weak wSelf = self;
    [renderer renderAdInView:adView completion:^(BOOL isRendered, NSError *error) {
        __typeof__(self) sSelf = wSelf;
        if (!sSelf) {
            return;
        }
        if (isRendered) {
            NSLog(@"Native ad has been rendered");
            //Register ad view for impression tracking and user clicks handling
            [renderer registerViewForImpression:adView];
            [renderer registerViewsForClickAction:@[adView.smaTitleLabel, adView.smaMainTextLabel, adView.smaIconView, adView.smaMediaView, adView.smaCTALabel]];
            //Add ad view on the screen
            [sSelf.view addSubview:adView];;
        } else {
            NSLog(@"Native ad rendering error %@", error);
        }
    }];
}
 
// Sent when the native ad fails to load an ad successfully
- (void)nativeAd:(SMANativeAd *)nativeAd didFailWithError:(NSError *)error {
    NSLog(@"Native ad failed with error: %@", error);
}
 
// A view controller that will be used to present modal view controllers
- (UIViewController *)presentingViewControllerForNativeAd:(SMANativeAd *)nativeAd {
    return self;
}
 
// Sent when TTL has expired, based on the timestamp from the ad header
- (void)nativeAdDidTTLExpire:(SMANativeAd *)nativeAd {
    NSLog(@"Native ad TTL has expired. Please load a new one. Tip: show Native before expiration for the best fill rate (you have about 5 minutes after loading completion).");
}

@end

3.) Lastly, build and run the app in the Simulator. The native ad should then appear on the screen.

 

Steps to Integrate an Interstitial Ad

1.) Adopt your ViewController to SMAInterstitialDelegate protocol. Implement at least the required SMAInterstitialDelegate methods. Create a method in ViewController class in order to load an interstitial and call it when you need. Then call this method.

Swift
Objective-C
Swift
// ViewController.swift
import UIKit
import SmaatoSDKInterstitial
 
class ViewController: UIViewController { 
    private var interstitial: SMAInterstitial?
 
    override func viewDidLoad() {
         super.viewDidLoad()
         // you can call this whenever you need the interstitial (not just in viewDidLoad())
         callWhenYouNeedInterstitial()
    }
 
    func callWhenYouNeedInterstitial() {
         // load interstitial ad with desired ad size
         SmaatoSDK.loadInterstitial(forAdSpaceId: "SMAATO_ADSPACE_ID", delegate: self)
    }
}
 
extension ViewController: SMAInterstitialDelegate {
    // Interstitial successfully loaded
    func interstitialDidLoad(_ interstitialResponse: SMAInterstitial) {
        interstitial = interstitialResponse
        interstitialResponse.show(from: self)
    }
     
    // Interstitial failed to load
    func interstitial(_ interstitial: SMAInterstitial?, didFailWithError error: Error) {
       print("Interstitial did fail loading with error: \(error.localizedDescription)")
    }
     
    // Interstitial ads TTL has expired    
    func interstitialDidTTLExpire(_ interstitial: SMAInterstitial) {
        print("Interstitial TTL has expired")
    }
}

Objective-C
// ViewController.m
#import "ViewController.h"
@import SmaatoSDKInterstitial;
 
// declare the ViewController to conform the SMAInterstitialDelegate protocol
@interface ViewController () 
@property (nonatomic, strong) SMAInterstitial *interstitial;
@end
 
@implementation ViewController
 
 - (void)viewDidLoad {
    [super viewDidLoad];
    // you can call this whenever you need the interstitial (not just in viewDidLoad())
    [self callWhenYouNeedInterstitial];
}
 
 - (void)callWhenYouNeedInterstitial {
    // load interstitial ad with desired ad size
    [SmaatoSDK loadInterstitialForAdSpaceId:@"SMAATO_ADSPACE_ID" delegate:self];
}
 
// Interstitial successfully loaded
- (void)interstitialDidLoad:(SMAInterstitial *)interstitial {
    self.interstitial = interstitial;
    [self.interstitial showFromViewController:self];
}
  
// Interstitial failed to load
- (void)interstitial:(SMAInterstitial *)interstitial didFailWithError:(NSError *)error {
    NSLog(@"Interstitial failed to load with error: %@", error.localizedDescription);
}
 
// Interstitial ads TTL has expired
- (void)interstitialDidTTLExpire:(SMAInterstitial *)interstitial {
    NSLog(@"Interstitial TTL has expired");
}
 
 
@end

2.) Lastly, build and run the app in the Simulator. The interstitial should then appear on the screen after loading.

 

Steps to Integrate a Rewarded Video Ad

1.) Adopt your ViewController to SMARewardedInterstitialDelegate protocol. Implement at least the required SMARewardedInterstitialDelegate methods. Create a method in ViewController class in order to load a Rewarded Video and call it when you need. Then call this method.

Swift
Objective-C
Swift
// ViewController.swift
import UIKit
import SmaatoSDKRewardedAds
 
class ViewController: UIViewController {  
    private var rewardedInterstitial: SMARewardedInterstitial?
 
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // you can call this whenever you need the rewarded ad (not just in viewDidLoad())
        callWhenYouNeedRewardedVideo()
    }
 
    func callWhenYouNeedRewardedVideo() {
        // load rewarded ad with desired ad size
        SmaatoSDK.loadRewardedInterstitial(forAdSpaceId: "SMAATO_ADSPACE_ID", delegate: self)
    }
}
 
extension ViewController: SMARewardedInterstitialDelegate {
   
    // Rewarded Video successfully loaded
    func rewardedInterstitialDidLoad(_ rewardedInterstitial: SMARewardedInterstitial) { 
        self.rewardedInterstitial = rewardedInterstitial
        rewardedInterstitial.show(from: self)
    }
     
    // Rewarded Video failed to load   
    func rewardedInterstitialDidFail(_ rewardedInterstitial: SMARewardedInterstitial?, withError error: Error) {       
        print("Rewarded Video failed to load with error: \(error.localizedDescription)")
    }
     
    // Rewarded Video TTL has expired    
    func rewardedInterstitialDidTTLExpire(_ rewardedInterstitial: SMARewardedInterstitial) {
        print("Rewarded Video TTL has expired")
    }
 
    // Rewarded interstitial finishes playing    
    func rewardedInterstitialDidReward(_ rewardedInterstitial: SMARewardedInterstitial) {
        print("Rewarded Video finishes playing")
    }
}

Objective-C
// ViewController.m
#import "ViewController.h"
@import SmaatoSDKRewardedAds;
 
// declare the ViewController to conform the SMARewardedInterstitialDelegate protocol
 
@interface ViewController () 
@property (nonatomic, strong) SMARewardedInterstitial *rewardedInterstitial;
@end
 
@implementation ViewController
 
 - (void)viewDidLoad {
    [super viewDidLoad];
    // you can call this whenever you need the rewarded ad (not just in viewDidLoad())
    [self callWhenYouNeedRewardedVideo];
}
 
 - (void)callWhenYouNeedRewardedVideo {
    // load rewarded ad with desired ad size
    [SmaatoSDK loadRewardedInterstitialForAdSpaceId:@"SMAATO_ADSPACE_ID" delegate:self];
}

// Rewarded Video successfully loaded
- (void)rewardedInterstitialDidLoad:(SMARewardedInterstitial *)rewardedInterstitial {
    self.rewardedInterstitial = rewardedInterstitial;
    [rewardedInterstitial showFromViewController:self];
}
  
// Rewarded Video failed to load
- (void)rewardedInterstitialDidFail:(SMARewardedInterstitial *)rewardedInterstitial withError:(NSError *)error {
    NSLog(@"Rewarded Video did fail loading with error: %@", error.localizedDescription);
}
 
// Rewarded Video TTL has expired
- (void)rewardedInterstitialDidTTLExpire:(SMARewardedInterstitial *)rewardedInterstitial {
    NSLog(@"Rewarded Video TTL has expired");
}
 
// Rewarded interstitial finishes playing
- (void)rewardedInterstitialDidReward:(SMARewardedInterstitial *)rewardedInterstitial {
    NSLog(@"Rewarded Video finishes playing");
}
 
@end

2.) Lastly, build and run the app in the Simulator. The video should then appear on the screen.

 

Steps to integrate Key-value targeting

SMAKeyValuePairs is the public component that allows creating targeting parameters.

A new class property of SMAKeyValuePairs type, named keyValuePairs, is introduced for each ad type and allows publishers to pass the keywords to be included to the request.

Constraints of setting SMAKeyValuePairs:

  • Can be added up to 7 values per key. If one key contains more than 7 values, the SDK adds only 7 values to the query request.
  • Can be added up to 7 key-value pairs per request. If the dictionary contains more than 7 key-value pairs, the SDK adds only 7 key-value pairs to the query request.
  • Key is String type and Value is an Array of String type.

keyValuePairs is a class property and not a property on an instance of the class. This property can be set for Banners, Interstitials and Rewarded Videos.

SMAKeyValuePairs public header:

@interface SMAKeyValuePairs : NSObject
 
// If aKey already exists in the dictionary, anObject is appended to the existing objects. 
// Otherwise, key-value pair is added.
- (void)addTargetingValue:(NSString *_Nonnull)anObject forKey:(NSString *_Nonnull)aKey;
 
// If aKey already exists in the dictionary, anObject takes its place. Otherwise, key-value pair is added.
- (void)setTargetingValue:(NSString *_Nonnull)anObject forKey:(NSString *_Nonnull)aKey;
 
// If aKey already exists in the dictionary, anObject takes its place. Otherwise, key-value pair is added.
- (void)setTargetingValues:(NSArray *_Nonnull)anObject forKey:(NSString *_Nonnull)aKey;
 
// Empties the dictionary of its values.
- (void)removeAllKeyValuePairs;
 
// Removes specific key-value pair from the targeting.
- (void)removeKeyValuePairWithKey:(NSString *_Nonnull)aKey;
 
// Returns all key-value pairs that will be added to the query request.
- (NSDictionary *_Nullable)allKeyValuePairs;
 
@end

Banners

Since this property is class type, once it is set it will have the same value for all Banner instances because it belongs to the class itself. So, there will always be one copy of Type property that all instances can use.

  • Initialize a SMAKeyValuePairs object and set your targeting parameters by using the public interface.
  • Set the key-value pairs object to SMABannerView.keyValuePairs property.
  • Call load method on Banner to apply the key-values for that request.
Swift
Objective-C
Swift
// ViewController.swift  
import Foundation
import SmaatoSDKBanner
   
class ViewController: UIViewController {
  // SMABannerView is linked in the Interface Builder with ViewController via IBOutlet.
	@IBOutlet var bannerView: SMABannerView?
    override func viewDidLoad() {
        super.viewDidLoad()
   
        // Let's create and set targeting parameters        
        let KVP = SMAKeyValuePairs()
		// replace with your key-value pairs configured within your SPX account
        KVP.setTargetingValue("30", forKey: "Age") 
		// replace with your key-value pairs configured within your SPX account
        KVP.setTargetingValues(["Demo", "Stage"], forKey: "Application")        
        SMABannerView.keyValuePairs = KVP
   
        // Send request, after replacing with your 'AdSpaceID' configured in your SPX account.        
        self.bannerView?.load(withAdSpaceId: "SMAATO_ADSPACE_ID", adSize: .xxLarge_320x50)
    }
}

Objective-C
// ViewController.m 
#import "ViewController.h"
@import SmaatoSDKBanner;
   
@interface ViewController ()
   
// SMABannerView is linked in the Interface Builder with ViewController via IBOutlet.
@property (nonatomic) IBOutlet SMABannerView *bannerView;
@end
   
@implementation ViewController
   
- (void)viewDidLoad {
    [super viewDidLoad];
   
    // Let's create and set targeting parameters    
    SMAKeyValuePairs *KVP = [SMAKeyValuePairs new];
	// replace with your key-value pairs configured within your SPX account
    [KVP setTargetingValue:@"30" forKey:@"Age"];
	// replace with your key-value pairs configured within your SPX account
    [KVP setTargetingValues:@[@"Demo", @"Stage"] forKey:@"Application"];    
    SMABannerView.keyValuePairs = KVP;
   
    // Send request, after replacing with your 'AdSpaceID' configured in your SPX account.
    [self.bannerView loadWithAdSpaceId:@"SMAATO_ADSPACE_ID" adSize:kSMABannerAdSizeXXLarge_320x50];
}
   
@end

Interstitials

Since this property is class type, once it is set it will have the same value for all Interstitial requests because it belongs to the class itself. So, there will be always one copy of type property that all

Interstitial requests can use.

  • Initialize a SMAKeyValuePairs object and set your targeting parameters by using the public interface
  • Set the key-value pairs object to SMAInterstitial.keyValuePairs property
  • Call loadInterstitial method to apply the key-values for that request.
Swift
Objective-C
Swift
// ViewController.swift  
import Foundation
import SmaatoSDKInterstitial
   
class ViewController: UIViewController {
   
    override func viewDidLoad() {
        super.viewDidLoad()
        callWhenYouNeedInterstitial()
    }
   
    func callWhenYouNeedInterstitial() {
        // Let's create and set targeting parameters        
        let KVP = SMAKeyValuePairs()
		// replace with your key-value pairs configured within your SPX account
        KVP.setTargetingValue("30", forKey: "Age")    
		// replace with your key-value pairs configured within your SPX account
        KVP.setTargetingValues(["Demo", "Stage"], forKey: "Application")        
        SMAInterstitial.keyValuePairs = KVP
   
        // Send request, after replacing with your 'AdSpaceID' configured in your SPX account.        
        SmaatoSDK.loadInterstitial(forAdSpaceId: "SMAATO_ADSPACE_ID", delegate: self)
    }
}

Objective-C
// ViewController.m  
#import "ViewController.h"
@import SmaatoSDKInterstitial;
   
@interface ViewController () 
@end
   
@implementation ViewController
   
- (void)viewDidLoad {
    [super viewDidLoad];
    [self callWhenYouNeedInterstitial];
}
   
- (void)callWhenYouNeedInterstitial {
    // Let's create and set targeting parameters    
    SMAKeyValuePairs *KVP = [SMAKeyValuePairs new];
	// replace with your key-value pairs configured within your SPX account 
    [KVP setTargetingValue:@"30" forKey:@"Age"];  
	// replace with your key-value pairs configured within your SPX account
    [KVP setTargetingValues:@[@"Demo", @"Stage"] forKey:@"Application"];
    SMAInterstitial.keyValuePairs = KVP;
 
    // Send request, after replacing with your 'AdSpaceID' configured in your SPX account.
    [SmaatoSDK loadInterstitialForAdSpaceId:@"SMAATO_ADSPACE_ID" delegate:self];
}
   
@end

Rewarded Videos

Since this property is class type, once it is set it will have the same value for all Rewarded Video requests because it belongs to the class itself. So, there will be always one copy of Type property that all video requests can use.

  • Initialize a SMAKeyValuePairs object and set your targeting parameters by using the public interface
  • Set the key-value pairs object to SMAInterstitial.keyValuePairs property
  • Call loadRewardedInterstitial method to apply the key-values for that request.
Swift
Objective-C
Swift
// ViewController.swift 
import Foundation
import SmaatoSDKRewardedAds
   
class ViewController: UIViewController {
   
    override func viewDidLoad() {
        super.viewDidLoad()
        callWhenYouNeedRewardedAds()
    }
   
    func callWhenYouNeedRewardedAds() {
        // Let's create and set targeting parameters        
        let KVP = SMAKeyValuePairs()
		// replace with your key-value pairs configured within your SPX account
        KVP.setTargetingValue("30", forKey: "Age")
		// replace with your key-value pairs configured within your SPX account
        KVP.setTargetingValues(["Demo", "Stage"], forKey: "Application")        
        SMARewardedInterstitial.keyValuePairs = KVP
   
        // Send request, after replacing with your 'AdSpaceID' configured in your SPX account.        
        SmaatoSDK.loadRewardedInterstitial(forAdSpaceId: "SMAATO_ADSPACE_ID", delegate: self)
    }
}

Objective-C
// ViewController.m  
#import "ViewController.h"
@import SmaatoSDKRewardedAds;
   
@interface ViewController () 
@end
   
@implementation ViewController
   
- (void)viewDidLoad {
    [super viewDidLoad];
    [self callWhenYouNeedRewardedAds];
}
   
- (void)callWhenYouNeedRewardedAds {
    // Let's create and set targeting parameters    
    SMAKeyValuePairs *KVP = [SMAKeyValuePairs new];
	// replace with your key-value pairs configured within your SPX account
    [KVP setTargetingValue:@"30" forKey:@"Age"]; 
	// replace with your key-value pairs configured within your SPX account
    [KVP setTargetingValues:@[@"Demo", @"Stage"] forKey:@"Application"];
    SMARewardedInterstitial.keyValuePairs = KVP;
   
    // Send request, after replacing with your 'AdSpaceID' configured in your SPX account.    
    [SmaatoSDK loadRewardedInterstitialForAdSpaceId:@"SMAATO_ADSPACE_ID" delegate:self];
}
   
@end


Last Modified: September 17, 2020 at 9:22 pm


© 2005-2020 Smaato, Inc. All Rights Reserved. Smaato® is a registered trademark of Smaato, Inc.

Privacy Policy | Cookie Policy | Support