Prioritizing iAd over adMob SpriteKit / Swift - swift

I integrated both iAd and adMob into my game, with adMob code only running when iAd fails to load. If the iAd does not fail loading the first ad, it works fine. Admob works like it should when iAd fails to load. However, when iAd fails but then loads the next ad, the adMob banner still exists and the iAd is not shown. How do I make it so that iAd loads even when adMob already is. Also, the iAd banner loads fine after failing to load when the adMob code is commented out. On an unrelated note, how do change the fill rate of adMob ads in the simulator? Thanks. This is my code in my GameViewController (iAd is called in gameScene):
import UIKit
import SpriteKit
import iAd
import GoogleMobileAds
class GameViewController: UIViewController, ADBannerViewDelegate {
var SH = UIScreen.mainScreen().bounds.height
let transition = SKTransition.fadeWithDuration(1)
var UIiAd: ADBannerView = ADBannerView()
var googleBannerView: GADBannerView!
override func viewWillAppear(animated: Bool) {
/* var BV = UIiAd.bounds.height
UIiAd.delegate = self
UIiAd.frame = CGRectMake(0, SH + BV, 0, 0)
self.view.addSubview(UIiAd) */
UIiAd.setTranslatesAutoresizingMaskIntoConstraints(false)
UIiAd.delegate = self
self.view.addSubview(UIiAd)
let viewsDictionary = ["bannerView":UIiAd]
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[bannerView]|", options: .allZeros, metrics: nil, views: viewsDictionary))
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[bannerView]|", options: .allZeros, metrics: nil, views: viewsDictionary))
}
override func viewWillDisappear(animated: Bool) {
UIiAd.delegate = nil
UIiAd.removeFromSuperview()
}
func bannerViewDidLoadAd(banner: ADBannerView!) {
var BV = UIiAd.bounds.height
UIView.beginAnimations(nil, context: nil)
UIView.setAnimationDuration(1) // Time it takes the animation to complete
UIiAd.alpha = 1 // Fade in the animation
UIView.commitAnimations()
println("iAd work")
}
func bannerView(banner: ADBannerView!, didFailToReceiveAdWithError error: NSError!) {
UIView.beginAnimations(nil, context: nil)
UIView.setAnimationDuration(1)
UIiAd.alpha = 0
UIView.commitAnimations()
googleBannerView = GADBannerView(adSize: kGADAdSizeSmartBannerLandscape)
googleBannerView.adUnitID = "ca-app-pub-3940256099942544/2934735716"
googleBannerView.rootViewController = self
var request: GADRequest = GADRequest()
googleBannerView.loadRequest(request)
googleBannerView.frame = CGRectMake(0, view.bounds.height - googleBannerView.frame.size.height, googleBannerView.frame.size.width, googleBannerView.frame.size.height)
self.view.addSubview(googleBannerView!)
println("iAd fail")
}
func showBannerAd() {
UIiAd.hidden = false
var BV = UIiAd.bounds.height
UIView.beginAnimations(nil, context: nil)
UIView.setAnimationDuration(1) // Time it takes the animation to complete
UIiAd.frame = CGRectMake(0, SH - BV, 2048, 0) // End position of the animation
UIView.commitAnimations()
}
func hideBannerAd() {
UIiAd.hidden = true
var BV = UIiAd.bounds.height
UIView.beginAnimations(nil, context: nil)
UIView.setAnimationDuration(1) // Time it takes the animation to complete
UIiAd.frame = CGRectMake(0, SH + BV, 0, 0) // End position of the animation
UIView.commitAnimations()
}
override func viewDidLoad() {
super.viewDidLoad()
self.UIiAd.hidden = true
self.UIiAd.alpha = 0
NSNotificationCenter.defaultCenter().addObserver(self, selector: "hideBannerAd", name: "hideadsID", object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "showBannerAd", name: "showadsID", object: nil)
let scene = GameScene(size: CGSize(width: 2048, height: 1356))
let skView = self.view as! SKView
skView.showsFPS = true
skView.showsNodeCount = true
skView.ignoresSiblingOrder = true
scene.scaleMode = SKSceneScaleMode.AspectFill
skView.presentScene(scene)
}
func bannerViewActionShouldBegin(banner: ADBannerView!, willLeaveApplication willLeave: Bool) -> Bool {
println("Clicked")
// let skView: SKView = self.view as! SKView
// skView.scene!.paused = true
return true
}
/* func bannerViewActionDidFinish(banner: ADBannerView!) {
let skView: SKView = self.view as! SKView
skView.scene!.paused = false
} */
override func prefersStatusBarHidden() -> Bool {
return true
}
}

You're not hiding your AdMob banner when iAd receives an ad in your bannerViewDidLoadAd(banner: ADBannerView!). So, your iAd banner is actually being displayed behind your AdMob banner.
Alternatively, you could create both your iAd and AdMob banners once in your viewDidLoad and hide or show them depending on if iAd receives an ad or not. Your iAd delegate methods would end up looking similar to this:
func bannerViewDidLoadAd(banner: ADBannerView!) {
UIView.beginAnimations(nil, context: nil)
// Show iAd
UIiAd.alpha = 1.0
// Hide AdMob
googleBannerView.alpha = 0.0
UIView.commitAnimations()
}
func bannerView(banner: ADBannerView!, didFailToReceiveAdWithError error: NSError!) {
UIView.beginAnimations(nil, context: nil)
// Hide iAd
UIiAd.alpha = 0.0
// Show AdMob
googleBannerView.alpha = 1.0
UIView.commitAnimations()
}
Check my answer here for a complete implementation.

I made an ad helper for swift, why don't you check it out, it does exactly what you want. It was primarily made for SpriteKit.
https://github.com/crashoverride777/Swift-iAds-and-AdMob-Helper

Related

iAds not showing on device after release to App Store?

I have recently released my game to the App Store. The iAd banner and medium ads are not showing up after almost a week now. All its showing isa blank space as in the following screenshots.
Can anyone check if there is anything wrong with my iAd code?
Before Release:
After Release:
import UIKit
import SpriteKit
import iAd
import Social
import GameKit
import StoreKit
class GameViewController: UIViewController, ADBannerViewDelegate, GKGameCenterControllerDelegate, ADInterstitialAdDelegate {
var scene: GameScene!
#IBOutlet var bannerView: ADBannerView!
var imageView = UIImageView()
var interAd = ADInterstitialAd()
var mediumRectAdView = ADBannerView(adType: ADAdType.MediumRectangle)
var interAdView = UIView()
var closeButton = UIButton(type: UIButtonType.System)
override func viewDidLoad() {
super.viewDidLoad()
let screenBounds: CGRect = UIScreen.mainScreen().bounds
bannerView = ADBannerView(frame:CGRectMake(0,0,50,screenBounds.width))
bannerView.center = CGPoint(x: screenBounds.width/2, y:screenBounds.height-bannerView.frame.size.height/2)
bannerView.delegate = self
bannerView.hidden = false//false //<<<<<<<<<<<<<<<<<<<<<<,
scene = GameScene(size:CGSize(width: 2048, height: 1536))
let skView = self.view as! SKView
scene.scaleMode = .AspectFill
skView.presentScene(scene)
skView.addSubview(bannerView)
if scene.productPurchased == true {
bannerView.hidden = true
}
firstScene = false
//self.interstitialPresentationPolicy = ADInterstitialPresentationPolicy.Manual
//Authenticate Game Center
NSNotificationCenter.defaultCenter().addObserver(self, selector:#selector(GameViewController.showAuthenticationViewController),name:PresentAuthenticationViewController, object: nil)
SGGameKit.sharedInstance.authenticateLocalPlayer()
// Share
NSNotificationCenter.defaultCenter().addObserver(self, selector: (#selector(GameViewController.displayShareSheet)), name:mySharePostKey, object: nil)
// Med iAD
NSNotificationCenter.defaultCenter().addObserver(self, selector: (#selector(GameViewController.loadMedAd)), name:myloadMedAdKey, object: nil)
// Interstitial iAD
NSNotificationCenter.defaultCenter().addObserver(self, selector: (#selector(GameViewController.loadInterAd)), name:myloadInterAdKey, object: nil)
// Hide Iad
NSNotificationCenter.defaultCenter().addObserver(self, selector: (#selector(GameViewController.hideAd)), name:myHideAdKey, object: nil)
}
func hideAd() {
print("Hiding Ad")
bannerView.hidden = true
}
func displayShareSheet() {
let initialText = "OMG! I got \(scene.score) points in Jumpox\n" + "https://itunes.apple.com/us/app/id1099659993)"
if let myImage = self.view?.pb_takeSnapshot() {
UIImageWriteToSavedPhotosAlbum(myImage, nil, nil, nil)
let activityViewController = UIActivityViewController(activityItems: [initialText,myImage as UIImage], applicationActivities: [])
activityViewController.excludedActivityTypes = [UIActivityTypeOpenInIBooks]
if UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiom.Phone {
self.presentViewController(activityViewController, animated: true, completion: {})
}
else {
let popup: UIPopoverController = UIPopoverController(contentViewController:activityViewController)
popup.presentPopoverFromRect(CGRectMake(self.view.frame.size.width / 2, self.view.frame.size.height / 4, 0, 0), inView: self.view, permittedArrowDirections: UIPopoverArrowDirection.Any, animated: true)
}
}
}
func loadMedAd() {
print("Loading loadMedAd")
closeButton = UIButton(type: UIButtonType.System)
closeButton.frame = CGRectMake(5, 5, 30, 30)
closeButton.layer.cornerRadius = 10
closeButton.setTitle("X", forState: .Normal)
closeButton.setTitleColor(UIColor.blackColor(), forState: .Normal)
closeButton.backgroundColor = UIColor.whiteColor()
closeButton.layer.borderColor = UIColor.blackColor().CGColor
closeButton.layer.borderWidth = 1
closeButton.addTarget(self, action: #selector(GameViewController.close), forControlEvents: UIControlEvents.TouchDown)
mediumRectAdView!.delegate = self
mediumRectAdView.center = self.view.center
mediumRectAdView.addSubview(closeButton)
interAdView = UIView(frame: self.view.frame)
self.view.addSubview(interAdView)
interAdView.addSubview(mediumRectAdView)
}
func loadInterAd() {
print("Loading loadInterAd")
interAd = ADInterstitialAd()
interAd.delegate = self
//if interAd.loaded {
closeButton.frame = CGRectMake(10, 10, 40, 40)
closeButton.layer.cornerRadius = 10
closeButton.setTitle("X", forState: .Normal)
closeButton.setTitleColor(UIColor.blackColor(), forState: .Normal)
closeButton.backgroundColor = UIColor.whiteColor()
closeButton.layer.borderColor = UIColor.blackColor().CGColor
closeButton.layer.borderWidth = 1
closeButton.addTarget(self, action: #selector(GameViewController.close), forControlEvents: UIControlEvents.TouchDown)
interAdView = UIView(frame: self.view.frame)
interAdView.frame = self.view.bounds
self.view.addSubview(interAdView)
interAd.presentInView(interAdView)
interAdView.addSubview(closeButton)
//}
//requestInterstitialAdPresentation()
}
func interstitialAd(interAd: ADInterstitialAd!, didFailWithError error: NSError!) {
print("Failed To Receive")
closeButton.removeFromSuperview()
interAdView.removeFromSuperview()
}
func close() {
closeButton.removeFromSuperview()
interAdView.removeFromSuperview()
}
func interstitialAdDidUnload(interstitialAd: ADInterstitialAd!) {
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func showAuthenticationViewController() {
let gameKitHelper = SGGameKit.sharedInstance
if let authenticationViewController = gameKitHelper.authenticationViewController {
self.presentViewController(authenticationViewController, animated: true,
completion: nil)
}
}
func gameCenterViewControllerDidFinish(gameCenterViewController: GKGameCenterViewController){
gameCenterViewController.dismissViewControllerAnimated(true, completion: nil)
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
}
iAd has been discontinued and is not accepting new apps into the network.
The iAd App Network will be discontinued as of June 30, 2016. Although
we are no longer accepting new apps into the network, advertising
campaigns may continue to run and you can still earn advertising
revenue until June 30. If you’d like to continue promoting your apps
through iAd until then, you can create a campaign using iAd Workbench.
I'm surprised the reviewer did not reject your submission. Look into AdMob, AppLovin, or the many other ad networks available for iOS.

Spritekit Supporting iAd

I have been looking everywhere on the web for tutorials on how to include iad banners in my spritekit game. For example I looked at this: Swift SpriteKit iAd but I got some errors, probaly due to the new swift 2 and swift 1. But could you explain what to do to include IAD in my spritekit game. Thank you in advance.
Make sure you have this code in your GameViewController. I just tested this out and it works for landscape and portrait mode.
class GameViewController: UIViewController, ADBannerViewDelegate {
//--------------------
//-----iAd Banner-----
//--------------------
var SH = UIScreen.mainScreen().bounds.height
let transition = SKTransition.fadeWithDuration(0)
var UIiAd: ADBannerView = ADBannerView()
override func viewWillAppear(animated: Bool) {
let BV = UIiAd.bounds.height
UIiAd.delegate = self
UIiAd.frame = CGRectMake(0, SH + BV, 0, 0)
self.view.addSubview(UIiAd)
}
override func viewWillDisappear(animated: Bool) {
UIiAd.delegate = nil
UIiAd.removeFromSuperview()
}
func bannerViewDidLoadAd(banner: ADBannerView!) {
UIView.beginAnimations(nil, context: nil)
UIView.setAnimationDuration(0.5) // Time it takes the animation to complete
UIiAd.alpha = 1 // Fade in the animation
UIView.commitAnimations()
}
func bannerView(banner: ADBannerView!, didFailToReceiveAdWithError error: NSError!) {
UIView.beginAnimations(nil, context: nil)
UIView.setAnimationDuration(0.5)
UIiAd.alpha = 0
UIView.commitAnimations()
}
func showBannerAd() {
UIiAd.hidden = false
let BV = UIiAd.bounds.height
UIView.beginAnimations(nil, context: nil)
UIView.setAnimationDuration(0.5) // Time it takes the animation to complete
UIiAd.frame = CGRectMake(0, SH - BV, UIScreen.mainScreen().bounds.width, 0)
UIView.commitAnimations()
}
func hideBannerAd() {
UIiAd.hidden = true
let BV = UIiAd.bounds.height
UIView.beginAnimations(nil, context: nil)
UIView.setAnimationDuration(0.5) // Time it takes the animation to complete
UIiAd.frame = CGRectMake(0, SH + BV, UIScreen.mainScreen().bounds.width, 0) //Beginning position of the ad
UIView.commitAnimations()
}
//--------------------
//-----View Loads-----
//--------------------
override func viewDidLoad() {
super.viewDidLoad()
//iAd Control
self.UIiAd.hidden = true
self.UIiAd.alpha = 0
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(GameViewController.hideBannerAd), name: "hideadsID", object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(GameViewController.showBannerAd), name: "showadsID", object: nil)
}
Add the following outside your class declarations. It doesn't matter what class you go to, as long as it's global so you can access them from any game scene.
//-------------
//-----Ads-----
//-------------
func showAds() {
NSNotificationCenter.defaultCenter().postNotificationName("showadsID", object: nil)
}
func hideAds() {
NSNotificationCenter.defaultCenter().postNotificationName("hideadsID", object: nil)
}
And then whenever you want to show ads in the specific scene or whenever, just call the "showAds()" function or "hideAds()" to hide them.

Interstitial iAd delayed after pressing button

I'm trying to setup iAd after clicking cancel button on JSSAlert. I have in JSSAlert function that set alpha for full view 0.7.. And in view controller I have function for iAd and set back alpha to 1.0...
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.title = "Vyhodnotenie testu"
self.showAlert()
}
func showAlert() {
func callback(){}
if numberOfPoints > 49 {
let customIcon = UIImage(named: "smile")
let alertview = JSSAlertView().show(self, title: "Gratulujeme! Uspeli ste.", text: "Dokončili ste test s počtom bodov \(numberOfPoints + 1) z \(maximumNumberOfPoints)!", buttonText: "OK!", color: UIColorFromHex(0x22c411, alpha: 1), iconImage: customIcon)
alertview.setTextTheme(.Light)
alertview.addAction(myCancelCallback)
self.navigationController?.navigationBar.alpha = 0.7
} else {
let customIcon = UIImage(named: "sad")
let alertview = JSSAlertView().show(self, title: "Ľutujeme! Neuspeli ste.", text: "Dokončili ste test s počtom bodov \(numberOfPoints + 1) z \(maximumNumberOfPoints)!", buttonText: "OK!", color: UIColorFromHex(0xd20606, alpha: 1), iconImage: customIcon)
alertview.addAction(myCancelCallback)
alertview.setTextTheme(.Light)
self.navigationController?.navigationBar.alpha = 0.7
}
}
func myCancelCallback() {
self.navigationController?.navigationBar.alpha = 1.0
self.interstitialPresentationPolicy = ADInterstitialPresentationPolicy.Automatic
}
func interstitialAdWillLoad(interstitialAd: ADInterstitialAd!) {
}
func interstitialAdDidLoad(interstitialAd: ADInterstitialAd!) {
interstitialAdView = UIView()
interstitialAdView.frame = self.view.bounds
view.addSubview(interstitialAdView)
interstitialAd.presentInView(interstitialAdView)
UIViewController.prepareInterstitialAds()
}
func interstitialAdActionDidFinish(var interstitialAd: ADInterstitialAd!) {
interstitialAd = nil
interstitialAdView.removeFromSuperview()
}
func interstitialAdActionShouldBegin(interstitialAd: ADInterstitialAd!, willLeaveApplication willLeave: Bool) -> Bool {
return true
}
func interstitialAd(interstitialAd: ADInterstitialAd!, didFailWithError error: NSError!) {
}
func interstitialAdDidUnload(var interstitialAd: ADInterstitialAd!) {
interstitialAd = nil
interstitialAdView.removeFromSuperview()
}
Alpha back to 1.0 in function myCancelCallback is working but iAd is delayed.. What can cause that delay? Or how can I deal with it?
I want to show iAd immediately after pressing OK!.
Video how it's working:
https://www.youtube.com/watch?v=r6LKN-cjaz8&feature=youtu.be
Update:
iAd App Network Shutdown As of December 31, 2016, the iAd App Network
is no longer available. If you'd like to promote your apps, you can
advertise using Search Ads, Apple News, or third party networks and
advertising sellers.
Reference: https://developer.apple.com/support/iad/
Here is what your gonna do, you have to create the interstitial including close button programmatically , i just made you a sample :
Add row in info.plist : View controller-based status bar appearance -> NO
in AppDelegate didFinishLaunchingWithOptions method add the following line to insure that status bar will be not hidden :
UIApplication.sharedApplication().setStatusBarHidden(false, withAnimation: UIStatusBarAnimation.None)
Here is a full sample view controller of how your gonna add the interstitial programmatically , but you only need to write animation when the interstitial is showing instead of just using addSubView. you can use animate transform translation you will find a lot of samples about that.
import UIKit
import iAd
class ViewController: UIViewController, ADInterstitialAdDelegate {
var interstitialAd:ADInterstitialAd!
var interstitialAdView: UIView = UIView()
var closeButton:UIButton!
override func viewDidLoad() {
super.viewDidLoad()
NSTimer.scheduledTimerWithTimeInterval(5, target: self, selector: "loadInterstitialAd", userInfo: nil, repeats: false)
}
func loadInterstitialAd() {
interstitialAd = ADInterstitialAd()
interstitialAd.delegate = self
}
func interstitialAdWillLoad(interstitialAd: ADInterstitialAd!) {
print("interstitialAdWillLoad")
}
func interstitialAdDidLoad(interstitialAd: ADInterstitialAd!) {
UIApplication.sharedApplication().setStatusBarHidden(false, withAnimation: UIStatusBarAnimation.Fade)
print("interstitialAdDidLoad")
UIApplication.sharedApplication().statusBarHidden = true
interstitialAdView = UIView()
interstitialAdView.frame = self.view.bounds
self.navigationController?.navigationBar.addSubview(interstitialAdView)
closeButton = UIButton(frame: CGRect(x: 15, y: 15, width: 20, height: 20))
//add a cross shaped graphics into your project to use as close button
closeButton.setBackgroundImage(UIImage(named: "close"), forState: UIControlState.Normal)
closeButton.addTarget(self, action: Selector("close"), forControlEvents: UIControlEvents.TouchDown)
self.navigationController?.navigationBar.addSubview(closeButton)
interstitialAd.presentInView(interstitialAdView)
UIViewController.prepareInterstitialAds()
}
func close() {
interstitialAdView.removeFromSuperview()
closeButton.removeFromSuperview()
interstitialAd = nil
UIApplication.sharedApplication().setStatusBarHidden(false, withAnimation: UIStatusBarAnimation.Fade)
}
func interstitialAdActionDidFinish(interstitialAd: ADInterstitialAd!) {
print("interstitialAdActionDidFinish")
UIApplication.sharedApplication().setStatusBarHidden(false, withAnimation: UIStatusBarAnimation.Fade)
}
func interstitialAdActionShouldBegin(interstitialAd: ADInterstitialAd!, willLeaveApplication willLeave: Bool) -> Bool {
return true
}
func interstitialAd(interstitialAd: ADInterstitialAd!, didFailWithError error: NSError!) {
print("didFailWithError")
}
func interstitialAdDidUnload(interstitialAd: ADInterstitialAd!) {
print("interstitialAdDidUnload")
close()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Release any cached data, images, etc that aren't in use.
}
}
Update: It might be you just have to call : UIViewController.prepareInterstitialAds() in viewDidLoad of your class to download the content of the interstitial so whenever you ask to present it will be ready and then might be no delay.

Hiding or Showing Google Ad View in Swift with Sprite Kit

In my game I would like there to be an Google Banner View in the main menu scene and game over scene. Here's what I have in the GameViewController:
override func viewWillLayoutSubviews(){
super.viewWillLayoutSubviews()
let skView = self.view as! SKView
googleBannerView = GADBannerView(adSize: kGADAdSizeSmartBannerPortrait)
googleBannerView.adUnitID = "ca-app-pub-3940256099942544/2934735716"
googleBannerView.rootViewController = self
var request: GADRequest = GADRequest()
googleBannerView.loadRequest(request)
googleBannerView.frame = CGRectMake(0, skView.bounds.height - googleBannerView.frame.size.height, googleBannerView.frame.size.width, googleBannerView.frame.size.height)
self.view.addSubview(googleBannerView!)
if skView.scene == nil{
let mainMenuScene = MainMenuScene(size: skView.bounds.size)
mainMenuScene.scaleMode = SKSceneScaleMode.AspectFill
mainMenuScene.backgroundColor = UIColor.whiteColor()
skView.presentScene(mainMenuScene)
}
}
func showBanner(){
if googleBannerView != nil{
self.googleBannerView!.hidden = false
var request: GADRequest = GADRequest()
self.googleBannerView.loadRequest(request)
}
}
func hideBanner(){
println("hideBanner() called")
self.googleBannerView.hidden = true
}
In the GameScene I have this:
override init(size: CGSize) {
super.init(size: size)
let gameViewController = GameViewController()
gameViewController.hideBanner()
When I run this it starts up fine, but when I press play it crashes and says: fatal error: unexpectedly found nil while unwrapping an Optional value. This doesn't make much sense because it can't be nil because I know there is an ad banner, right? What I am doing wrong. Thank you in advance.
-Vinny
There could possibly be an error in your show banner function. Try taking out the exclamation in:
self.googleBannerView!.hidden = false
If the banner view is not nil, then it doesn't need to unwrapped

How to implement Interstitial iAds in Swift(Xcode 6.1)

I am trying to figure out how to switch over from my banner view iAds to interstitial iAds in order to free up space for a tabbed controller. For some reason I am completely unable to find any resource for even getting started on these ads with swift.
Could anyone please give me some information on interstitial iAds with Swift and how I can implement them in a project.
Here is a relatively cleaner and easier to follow way to implement Interstitial Ads since this way doesn't require the use of NSNotificationCentre
import UIKit
import iAd
class ViewController: UIViewController, ADInterstitialAdDelegate {
var interstitialAd:ADInterstitialAd!
var interstitialAdView: UIView = UIView()
override func viewDidLoad() {
super.viewDidLoad()
loadInterstitialAd()
}
func loadInterstitialAd() {
interstitialAd = ADInterstitialAd()
interstitialAd.delegate = self
}
func interstitialAdWillLoad(interstitialAd: ADInterstitialAd!) {
}
func interstitialAdDidLoad(interstitialAd: ADInterstitialAd!) {
interstitialAdView = UIView()
interstitialAdView.frame = self.view.bounds
view.addSubview(interstitialAdView)
interstitialAd.presentInView(interstitialAdView)
UIViewController.prepareInterstitialAds()
}
func interstitialAdActionDidFinish(interstitialAd: ADInterstitialAd!) {
interstitialAdView.removeFromSuperview()
}
func interstitialAdActionShouldBegin(interstitialAd: ADInterstitialAd!, willLeaveApplication willLeave: Bool) -> Bool {
return true
}
func interstitialAd(interstitialAd: ADInterstitialAd!, didFailWithError error: NSError!) {
}
func interstitialAdDidUnload(interstitialAd: ADInterstitialAd!) {
interstitialAdView.removeFromSuperview()
}
And it may help if you put println("Function Name") in each function just to keep track of your Interstitial Ads process. If you have any questions and or a way to improve this block of code please leave a comment. Thank You
Here is how i use in my project
//adding iAd framework
import iAd
//conform iAd delegate
class ViewController: UIViewController,ADInterstitialAdDelegate
//create instance variable
var interstitial:ADInterstitialAd!
//default iAd interstitials does not provide close button so we need to create one manually
var placeHolderView:UIView!
var closeButton:UIButton!
override func viewDidLoad() {
super.viewDidLoad()
//iAD interstitial
NSNotificationCenter.defaultCenter().addObserver(self, selector: ("runAd:"), name:UIApplicationWillEnterForegroundNotification, object: nil)
}
//iAD interstitial
func runAd(notification:NSNotification){
var timer = NSTimer.scheduledTimerWithTimeInterval(3.0, target: self, selector: Selector("dislayiAdInterstitial"), userInfo: nil, repeats: false)
cycleInterstitial()
}
func cycleInterstitial(){
// Clean up the old interstitial...
// interstitial.delegate = nil;
// and create a new interstitial. We set the delegate so that we can be notified of when
interstitial = ADInterstitialAd()
interstitial.delegate = self;
}
func presentInterlude(){
// If the interstitial managed to load, then we'll present it now.
if (interstitial.loaded) {
placeHolderView = UIView(frame: self.view.frame)
self.view.addSubview(placeHolderView)
closeButton = UIButton(frame: CGRect(x: 270, y: 25, width: 25, height: 25))
closeButton.setBackgroundImage(UIImage(named: "error"), forState: UIControlState.Normal)
closeButton.addTarget(self, action: Selector("close"), forControlEvents: UIControlEvents.TouchDown)
self.view.addSubview(closeButton)
interstitial.presentInView(placeHolderView)
}
}
// iAd Delegate Mehtods
// When this method is invoked, the application should remove the view from the screen and tear it down.
// The content will be unloaded shortly after this method is called and no new content will be loaded in that view.
// This may occur either when the user dismisses the interstitial view via the dismiss button or
// if the content in the view has expired.
func interstitialAdDidUnload(interstitialAd: ADInterstitialAd!){
placeHolderView.removeFromSuperview()
closeButton.removeFromSuperview()
interstitial = nil
cycleInterstitial()
}
func interstitialAdActionDidFinish(_interstitialAd: ADInterstitialAd!){
placeHolderView.removeFromSuperview()
closeButton.removeFromSuperview()
interstitial = nil
println("called just before dismissing - action finished")
}
// This method will be invoked when an error has occurred attempting to get advertisement content.
// The ADError enum lists the possible error codes.
func interstitialAd(interstitialAd: ADInterstitialAd!,
didFailWithError error: NSError!){
cycleInterstitial()
}
//Load iAd interstitial
func dislayiAdInterstitial() {
//iAd interstitial
presentInterlude()
}
func close() {
placeHolderView.removeFromSuperview()
closeButton.removeFromSuperview()
interstitial = nil
}
I know this is old - but I just came across
override func prepareForSegue(segue: UIStoryboardSegue,
sender: AnyObject?) {
let destination = segue.destinationViewController
as UIViewController
destination.interstitialPresentationPolicy =
ADInterstitialPresentationPolicy.Automatic
}
If you add this to your app delegate, you'll avoid that 3 second delay suggested above.
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
UIViewController.prepareInterstitialAds()
return true
}