Get Started with Vungle - iOS SDK v. 5.x (Swift)

Contents

Before You Get Started

  • The Vungle iOS SDK v. 5.x only supports iOS 8+.
  • The Vungle iOS SDK v. 5.x 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 newest iOS SDK (since v. 4.0.8) was released in support of the newest Xcode 8.0. Ensure you are using Xcode 8.0 or higher for a smooth integration.
  • The source code referenced here is available on our public GitHub repo.

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.x"

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.x. If you are updating from a previous version of the Vungle SDK, first remove the VungleSDK.framework directory completely before adding the new SDK. Then 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
  • libsqlite3.dylib or libsqlite3.tbd
  • MediaPlayer.framework
  • QuartzCore.framework
  • StoreKit.framework
  • SystemConfiguration.framework
  • UIKit.framework
  • WebKit.framework

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

Create a Bridging Header File

  1. Create a new Objective-C file in your project (File  New  File [Objective-C File]).
  2. Xcode will ask if you'd like to create a bridging header file between Objective-C and Swift. Accept this prompt.
  3. Delete the new Objective-C file (${YOURPROJ}-Bridging-Header.m), but retain the bridging header file ${YOURPROJ}-Bridging-Header.h.
  4. In the Bridging header file, import the Vungle SDK by adding the following:
    #import <VungleSDK/VungleSDK.h>
    

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:

let appID = "Your_AppID_Here";
var placementIDsArray:Array<String> = ["<Your_PlacementID_1>", "<Your_PlacementID_2>", "<Your_PlacementID_3>"];

var sdk:VungleSDK = VungleSDK.shared()
do {
try sdk.start(withAppId: appID, placements: placementIDsArray)
}
catch let error as NSError {
print("Error while starting VungleSDK : \(error.domain)")
return;
}

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.

var sdk:VungleSDK = VungleSDK.shared()
do {
try sdk.loadPlacement(withID: <Your_PlacementID>)
}
catch let error as NSError {
print("Unable to load placement with reference ID :\(<Your_PlacementID>), Error: \(error)")

return
}

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: 

func vungleAdPlayabilityUpdate(_ isAdPlayable: Bool, placementID: String?) {
       if (placementID == <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:

var sdk:VungleSDK = VungleSDK.shared()
do {
try sdk.playAd(self, options: nil, placementID: kVungleTestPlacementID01)
}
catch let error as NSError {
print("Error encountered playing ad: + \(error)");
}

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:

var sdk:VungleSDK = VungleSDK.shared()
// Attach
sdk.delegate = <yourDelegateInstance> as VungleSDKDelegate
// Detach
sdk.delegate = 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 to check as the 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 NSString 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:

let options: NSDictionary = NSDictionary(dictionary: [VunglePlayAdOptionKeyUser: "test_user_id",
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!"])
do {
try self.sdk.playAd(self, options: (options as! [AnyHashable : Any]), placementID: PlacementID)
}
catch let error as NSError {
print("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:

var sdk:VungleSDK = VungleSDK.shared()
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: 

- (void)attachLogger:(id<VungleSDKLogger>)logger;

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

- (void)detachLogger:(id<VungleSDKLogger>)logger;

Have more questions? Submit a request

Comments