Get Started with Vungle - iOS SDK v. 5

Contents

Before You Get Started

  • The Vungle iOS SDK v. 5 supports iOS 8+.
  • The Vungle iOS SDK v. 5 has been tested with iOS 11 beta/GM Seed.
  • The Vungle iOS SDK v. 5 supports both 32bit and 64bit apps.
  • Integration requires you to have a Vungle account. If you don't yet have an account, create one before proceeding.
  • Our iOS SDK supports Xcode 8.0 and 9.0. Ensure you are using Xcode 8.0 or higher for a smooth integration.

Step 1. Add the Vungle Framework to your Xcode Project

Add the VungleSDK.framework to your Project

There are two ways to add Vungle to your Xcode project: using Cocoapods or manual integration.

Cocoapods

The Vungle SDK is available through Cocoapods. Add Vungle to your project by adding the following line into your project’s podfile.

 pod "VungleSDK-iOS", "5.3.0"

After that, a quick pod install run should update your project with the latest version of our iOS SDK. At this point you can skip down to “Step 2. Remove the iOS Status Bar”.

Manual Integration

Download Vungle SDK v5. If you are updating from a previous version of the Vungle SDK, first remove the VungleSDK.framework directory completely before adding the new SDK.

Find the extracted files and drag the VungleSDK.framework directory into Xcode under Frameworks. Be sure to add the VungleSDK.framework folder as a group (yellow folder) and not as a reference (blue folder). 

Add Other Required Frameworks

The Vungle SDK requires that you link a few other native frameworks to your project, so click on your project in Project Navigator and go to General → Linked Frameworks and Libraries.

Many of these frameworks are already included as a default for most Xcode projects, but be sure to add any of the following that are not already included:

  • AdSupport.framework
  • AudioToolbox.framework
  • AVFoundation.framework
  • CFNetwork.framework
  • CoreGraphics.framework
  • CoreMedia.framework
  • Foundation.framework
  • libz.dylib or libz.tbd
  • MediaPlayer.framework
  • QuartzCore.framework
  • StoreKit.framework
  • SystemConfiguration.framework
  • UIKit.framework
  • WebKit.framework
    Note: Set the WebKit.framework Status to 'Optional' if you have iOS 7 as a deployment target.

Make sure that the VungleSDK framework appears under Linked Frameworks and Libraries.  

Add the “-ObjC” Linker Flag

Click on your project in Project Navigator​ and go to Build Settings → Linking → Other Linker Flags​. Add -ObjC​ to Other Linker Flags​.

Step 2. Remove the iOS Status Bar

Although this step is not required, we recommend that you remove the iOS status bar to ensure that Vungle's ad interaction and presentation perform smoothly. To remove the status bar, open your Info.plist, add the key View controller-based status bar appearance​, and set it to No.

Step 3. Add Code

Initialize the SDK

Note:​ A default placement is created for each app automatically. You must provide its placement reference ID in this initialization step whether or not you plan to take advantage of the placements functionality. If you create multiple placements, provide all the reference IDs.

Initialize the SDK as soon as your app starts in order to give the SDK enough time to cache an ad for the auto-cached placement. You will need the App ID and all the placement reference IDs you want to use in your app (both active and inactive) to initialize the SDK. You can find these IDs in the Vungle Dashboard (refer to Setting up Placements in Your Vungle Dashboard).

- (BOOL)startWithAppId:(nonnull NSString *)appID placements:(nonnull NSArray *)placements error:(NSError **)error;

Sample code:

#import <VungleSDK/VungleSDK.h>
...
NSError* error;
NSString* appID = @"Your_AppID_Here"; NSArray* placementIDsArray = @[@"<Your_PlacementID_1>", @"<Your_PlacementID_2>", @"<Your_PlacementID_3>"]; VungleSDK* sdk = [VungleSDK sharedSDK]; [sdk startWithAppId:appID placements:placementIDsArray error:&error];

Once the SDK is initialized successfully, the following callback method is called:

- (void)vungleSDKDidInitialize;

Refer to the “Delegate Callbacks” section of this article.

You can also check the status of the SDK initialization with the following property:

@property (atomic, readonly, getter=isInitialized) BOOL initialized;

After the SDK is initialized, it automatically caches an ad for the placement you selected as Auto Cached in the Vungle Dashboard. We recommend selecting the most viewed placement for auto-caching.

Once an ad is cached successfully, the vungleAdPlayabilityUpdate callback method is called with the placement reference ID matching your Auto Cached placement. (Refer to the “Check Ad Availability for a Placement” section of this article.) 

Load an Ad for a Placement

For placements other than the auto-cached placement, call loadPlacementWithID method to load an ad.

- (BOOL)loadPlacementWithID:(NSString *)placementID error:(NSError **)error;

Sample code: 

NSError* error;
VungleSDK* sdk = [VungleSDK sharedSDK]; [sdk loadPlacementWithID:"<Your_PlacementID>" error:&error];

Refer to the “Check Ad Availability for a Placement” section of this article.

Check Ad Availability for a Placement

Once the SDK finishes caching an ad for a placement, the following callback method is called:

- (void)vungleAdPlayabilityUpdate:(BOOL)isAdPlayable placementID:(nullable NSString *)placementID; 

Sample code: 

- (void)vungleAdPlayabilityUpdate:(BOOL)isAdPlayable placementID:(NSString *)placementID {
    if([placementID isEqualToString:@"<Your_PlacementID>"]) {
        self.playButtonPlacement1.enabled = isAdPlayable;
    }
}

Note: For the auto-cached placement, only when an ad becomes available is this callback method called. The SDK will keep requesting an ad for the auto-cached placement. For all other placements, this callback method is called in case of “Load Failed” (isAdPlayable returns ‘NO’ in this case).

You can also check the ad availability for a placement with the following property: 

- (BOOL)isAdCachedForPlacementID:(nonnull NSString *)placementID;

Play an Ad

After you make sure that an ad is ready for a placement, you can play the ad with the following method:

- (BOOL)playAd:(UIViewController *)controller options:(nullable NSDictionary *)options placementID:(nullable NSString *)placementID error:( NSError *__autoreleasing _Nullable *_Nullable)error;

Sample Code:

VungleSDK* sdk = [VungleSDK sharedSDK];
NSError *error;
[self.sdk playAd:self options:nil placementID:@"<Your_PlacementID_1>" error:&error];
if (error) {
    NSLog(@"Error encountered playing ad: %@", error);
}

Flex Feed Ads

Vungle SDK v.5.3 now supports Flex Feed ads. This is the first ad format that does not require a full screen; instead, the publisher determines the exact dimensions and location of the ad container within their app. These ad containers can be in collection views or table views.

Loading a Flex Feed Ad

Loading a Flex Feed ad is the same as loading a fullscreen ad; however, the placement must be configured to support Flex Feed. Contact your Vungle account manager to enable Flex Feed for a placement.

Displaying a Flex Feed Ad

Displaying Flex Feed ads differs from displaying fullscreen ads. With Flex Feed ads, you must first create a container for the ad. This container is a UIView. You can place said UIView anywhere on the screen. The ad will scale to any size of container, but keep in mind that very low resolution will make ads less visible. You must then call the addAdViewToView function to associate the container with the Flex Feed ad.

Function overview:


/**
 * Pass in an UIView which acts as a container for the ad experience. This view container may be placed in random positions.
 * @param publisherView container view in which an ad will be displayed
 * @param options A reference to an instance of NSDictionary with customized ad playback options
 * @param placementID The placement defined on the Vungle dashboard
 * @param error An optional double reference to an NSError. In case this method returns `NO` it will be non-nil
 * @return YES/NO in case of success/error while presenting an AdUnit
 */
- (BOOL)addAdViewToView:(UIView *)publisherView withOptions:(nullable NSDictionary *)options placementID:(nullable NSString *)placementID error:( NSError *__autoreleasing _Nullable *_Nullable)error;

Sample code:


NSError *error;
NSDictionary *options = @{};
VungleSDK* sdk = [VungleSDK sharedSDK];
[sdk addAdViewToView:_FlexFeedViewArea withOptions:options placementID: error:&error];
if (error) 
{
        NSLog(@"Error encountered while playing an ad: %@", error);
}

Closing a Flex Feed Ad

Due to the nature of Flex Feed ads, a user can stop viewing the video without closing the ad. You must therefore tell the SDK to dismiss the ad when it is no longer on screen. To do this, call the finishedDisplayingAd function.

Function overview:


/**
 * This method must be called when the publisher is confident that they are finished displaying the ad unit.
 * This signals to the SDK that a new ad may be fetched or a different ad may be displayed. This will
 * be called in conjunction with `addViewToView:containedInViewController:withOptions:placementID:error:`
 */
- (void)finishedDisplayingAd;

Sample code:


//Ad is no longer on screen
VungleSDK* sdk = [VungleSDK sharedSDK];
[sdk finishedDisplayingAd];

Delegate Callbacks

You can receive callbacks from the SDK with VungleSDKDelegate. There are four callback methods in the delegate in which you are notified of the SDK events.

You can attach and detach your delegate with:

// Attach
[[VungleSDK sharedSDK] setDelegate:yourDelegateInstance];
// Detach
[[VungleSDK sharedSDK] setDelegate:nil];

Note: Remember to clear the registered delegate when it's no longer needed to avoid memory leaks. 

The following method is called when the SDK is about to play a video ad. This is a great place to pause gameplay, sound effects, animations, etc.

- (void)vungleWillShowAdForPlacementID:(nullable NSString *)placementID;

The following method is called when the SDK is about to close an ad. This is a great place to reward your user and resume gameplay, sound effects, animations, etc.  


- (void)vungleWillCloseAdWithViewInfo:(VungleViewInfo *)info placementID:(NSString *)placementID;

VungleViewInfo includes the following properties for you to check a result of ad play:

@interface VungleViewInfo : NSObject 
//Represents a BOOL whether or not the video can be considered a completed view.
@property (nonatomic, readonly) NSNumber *completedView;
//The time in seconds that the user watched the video.
@property (nonatomic, readonly) NSNumber *playTime;
//Represents a BOOL whether or not the user clicked the download button.
@property (nonatomic, readonly) NSNumber *didDownload;
@end

The following method is called when the SDK has changed ad availability status. The isAdPlayable boolean denotes the new playability of a specific placementID.

- (void)vungleAdPlayabilityUpdate:(BOOL)isAdPlayable placementID:(NSString *)placementID;

Refer to the “Check Ad Availability for a Placement” section of this article.

The following method is called when the SDK is initialized successfully:

- (void)vungleSDKDidInitialize;

Customization Options

Use these options to customize the ad experience for playback.

Note: Rewarded ads are in some cases referred to as incentivized ads; both terms always refer to the same kind of ad. In the SDK code and in our Reporting API, we use the term 'incentivized'.

Option Keys

Default Value / Type

Description

VunglePlayAdOptionKeyOrientations

autorotate

UIInterfaceOrientationMaskAll

An NSNumber representing a bitmask with orientations

Sets the orientation of the ad. We recommend allowing ads to autorotate, even if your app is in portrait. This way, the user has the option to watch full-size videos, resulting in a better user experience. You can achieve this by setting the orientation on a view controller level (rather than a project level).

VunglePlayAdOptionKeyUser

nil

NSString

Sets your user ID. The value is passed to Vungle server, and then sent to your server through server-to-server callback system if an placement is set to “Rewarded”.

VunglePlayAdOptionKeyIncentivizedAlertTitleText

nil

NSString

String that is used as the title of the alert dialog presented when a user closes an incentivized ad experience prematurely.

VunglePlayAdOptionKeyIncentivizedAlertBodyText

“Are you sure you want to skip this ad? If you do, you might not get your reward”

NSString

String that is used as the body text of the alert dialog presented when a user closes an incentivized ad experience prematurely.

VunglePlayAdOptionKeyIncentivizedAlertCloseButtonText

“Close”

NSString

String title for the close button text of the alert dialog presented when a user closes an incentivized ad experience prematurely.

VunglePlayAdOptionKeyIncentivizedAlertContinueButtonText

“Continue”

NSString

String title for the close button text of the alert dialog presented when a user closes an incentivized ad experience prematurely.

 Sample code:

NSDictionary *options = @{VunglePlayAdOptionKeyOrientations: @(UIInterfaceOrientationMaskLandscape),
                          VunglePlayAdOptionKeyUser: @"userGameID",
                          VunglePlayAdOptionKeyIncentivizedAlertBodyText : @"If the video isn't completed you won't get your reward! Are you sure you want to close early?",
                          VunglePlayAdOptionKeyIncentivizedAlertCloseButtonText : @"Close",
                          VunglePlayAdOptionKeyIncentivizedAlertContinueButtonText : @"Keep Watching",
                          VunglePlayAdOptionKeyIncentivizedAlertTitleText : @"Careful!"};

// Pass in dict of options, play ad
NSError *error;
[self.sdk playAd:self options:options placementID: error:&error];

if (error) {
    NSLog(@"Error encountered playing ad: %@", error);
}

Mute Option

The Vungle SDK instance offers the option to play ads with the sound disabled. You can set the muted property to true before issuing a playAd().  

Sample code:

VungleSDK* sdk = [VungleSDK sharedSDK];
self.sdk.muted = true;

Note: This option only applies to the standard ad type. The muted option for Dynamic Template ads is available to configure on the dashboard.

Debug

If you need SDK information, you can get it by using this property:

- (NSDictionary *)debugInfo;

If you want the SDK to output logs, use the following method: 

- (void)setLoggingEnabled:(BOOL)enable;

VungleSDKLogger Protocol 

@protocol VungleSDKLogger 
- (void)vungleSDKLog:(NSString*)message;
@end

The VungleSDK singleton sends logging events to any attached class following the VungleSDKLogger protocol. The log event contains the NSString value that is also printed to console (if logging has been enabled). To attach your logger, use the following: 

[sdk attachLogger:yourLoggerInstance];

As mentioned above, it's important to clear out attached loggers from the Vungle SDK. Loggers can be detached using the following approach: 

[sdk detachLogger:yourLoggerInstance];

assetLoader Protocol 

@protocol VungleAssetLoader
/**
 * should return a valid NSData containing the (raw) data of an image for the specified path or nil. */
- (NSData*)vungleLoadAsset:(NSString*)path;

/**
 * should return a valid UIImage for the specified path, or nil.
 */
- (UIImage*)vungleLoadImage:(NSString*)path;
@end
Have more questions? Submit a request

Comments