Interstitial iAd delayed after pressing button - swift

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.

Related

rewardedAdDidDismiss function not getting called

I'm implementing rewarded ads in a chat application and using tab bars with it. I'm having a problem with rewarded that whenever I call the function rewardedAd = createAndLoadRewardedAd() in viewDidLoad and the ad gets presented when I dismiss the ad the function rewardedAdDidDismiss gets called without a problem.
override func viewDidLoad() {
super.viewDidLoad()
timerLabelDisplay.layer.opacity = 0.0
rewardedAd = createAndLoadRewardedAd()
}
Now as we all now viewDidLoad will be called only one time, and this will not help me if i change the tab bar and get back to it, this mean my ad won't load. So what i did, is i put the rewardedAd = createAndLoadRewardedAd() in viewWillAppear
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
removeAdsFreeButton.isEnabled = false
removeAdsFreeButton.backgroundColor = .gray
rewardedAd = createAndLoadRewardedAd()
}
Now when i did this everything seems to be perfect, when i change the tab bar and go back again, my reward ad is loading without a problem. However now, when the ad is dissmissed, the function rewardedAdDidDismiss() is not getting called, and i need it to be called and i didn't know why?
here it is the full code:
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
removeAdsFreeButton.isEnabled = false
removeAdsFreeButton.backgroundColor = .gray
rewardedAd = createAndLoadRewardedAd()
}
override func viewDidLoad() {
super.viewDidLoad()
timerLabelDisplay.layer.opacity = 0.0
}
func createAndLoadRewardedAd() -> GADRewardedAd? {
rewardedAd = GADRewardedAd(adUnitID: "ca-app-pub-3940256099942544/1712485313")
rewardedAd?.load(GADRequest()) { error in
if error != nil {
print("Loading reward ad failed there is a problem here")
} else {
UIView.animate(withDuration: 1.0) {
self.removeAdsFreeButton.isEnabled = true
self.removeAdsFreeButton.layer.backgroundColor = UIColor(named: "ChatiwRed")!.cgColor
self.removeAdsFreeButton.layer.backgroundColor = UIColor(named: "ChatiwYello")!.cgColor
self.removeAdsFreeButton.layer.backgroundColor = UIColor(named: "ChatiwRed")!.cgColor
}
self.removeAdsFreeButton.pulseAnimation()
}
}
return rewardedAd
}
var didUserGotReward = false
func rewardedAdDidDismiss(_ rewardedAd: GADRewardedAd) {
self.rewardedAd = createAndLoadRewardedAd()
print("ok now show the timer")
if didUserGotReward {
UIView.animate(withDuration: 5) {
self.timerLabelDisplay.layer.opacity = 1.0
}
timerLabelDisplay.pulseAnimation()
didUserGotReward = false
}
}

Pinning a UIButton to a specific location on a photograph

urbanPan
Hi,
I have a photograph with UI buttons on top. The UI buttons need to be at very specific and precise locations on the photograph.
When I resize the photograph (for example, for different devices), the UI buttons never stay in alignment.
Containers do not work as they are relative to the screen size and orientation rather than the aspect and dimensions of the photograph.
For example, when the photo is uncropped on larger devices such as the iPad, then the container rules are no longer relevant.
Pinning does not work as the absolute values cannot be scaled up and resized.
I know what I’m trying to achieve is possible as it is common and seen in other apps. However, the alignment and constraints in Xcode do not appear to facilitate this?
I’m sure I’m missing something. Any ideas, greatly appreciated.
See urbanPan image below or urbanPan.io for Github files.
urbanPan
Blessup,
UrbanSmash
Although the issue appears to be more directly related to the Main.Storyboard layout, here is the code for the ViewController.swift
//
// ViewController.swift
// urbanPan
//
// Created by URBANSMASH pro on 29/08/2019.
// Copyright © 2019 Play it on Pan. All rights reserved.
//
import UIKit
import AVFoundation
import AudioKit
class ViewController: UIViewController, AVAudioPlayerDelegate {
var player : AVAudioPlayer!
let sounds = ["Rest", "2-F3", "2-FS3", "2-G3", "2-GS3", "2-A3", "2-AS3", "2-B3", "2-C4", "2-CS4", "2-D4", "2-DS4", "2-E4", "2-F4", "2-FS4", "2-G4", "2-GS4", "2-A4", "2-AS4", "2-B4", "2-C5", "2-CS5", "2-D5", "2-DS5", "2-E5", "2-F5", "2-FS5", "2-G5", "2-GS5", "2-A5", "2-AS5", "2-B5", "2-C6"]
var noteNum = 0
let conductor = Conductor.shared
var isPlaying = false
var currentSound = 0
override func viewDidLoad() {
super.viewDidLoad()
conductor.midi.addListener(self)
conductor.loadSamples(byIndex: currentSound)
}
#IBAction func noteReleased(_ sender: UIButton) {
noteNum = sender.tag
// player.currentTime = 0
stopSound()
}
#IBAction func notePlayed(_ sender: UIButton) {
noteNum = sender.tag
// player.currentTime = 0
playSound()
}
func stopSound() {
noteOff(note: MIDINoteNumber(noteNum))
}
func playSound() {
noteOn(note: MIDINoteNumber(noteNum))
}
func noteOn(note: MIDINoteNumber) {
DispatchQueue.main.async {
self.conductor.playNote(note: note, velocity: 100, channel: 0)
}
}
func noteOff(note: MIDINoteNumber) {
DispatchQueue.main.async {
self.conductor.stopNote(note: note, channel: 0)
}
}
}
extension ViewController: AKMIDIListener {
func receivedMIDINoteOn(noteNumber: MIDINoteNumber, velocity: MIDIVelocity, channel: MIDIChannel) {
DispatchQueue.main.async {
self.conductor.playNote(note: noteNumber, velocity: velocity, channel: channel)
}
}
func receivedMIDINoteOff(noteNumber: MIDINoteNumber, velocity: MIDIVelocity, channel: MIDIChannel) {
DispatchQueue.main.async {
self.conductor.stopNote(note: noteNumber, channel: channel)
}
}
// MIDI Controller input
func receivedMIDIController(_ controller: MIDIByte, value: MIDIByte, channel: MIDIChannel) {
AKLog("Channel: \(channel + 1) controller: \(controller) value: \(value)")
//conductor.controller(controller, value: value)
}
// MIDI Pitch Wheel
func receivedMIDIPitchWheel(_ pitchWheelValue: MIDIWord, channel: MIDIChannel) {
//conductor.pitchBend(pitchWheelValue)
}
// After touch
func receivedMIDIAfterTouch(_ pressure: MIDIByte, channel: MIDIChannel) {
conductor.afterTouch(pressure)
}
func receivedMIDISystemCommand(_ data: [MIDIByte]) {
// do nothing: silence superclass's log chatter
}
// MIDI Setup Change
func receivedMIDISetupChange() {
AKLog("midi setup change, midi.inputNames: \(conductor.midi.inputNames)")
let inputNames = conductor.midi.inputNames
inputNames.forEach { inputName in
conductor.midi.openInput(name: inputName)
}
}
func setSpeakersAsDefaultAudioOutput() {
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category.playAndRecord, options: AVAudioSession.CategoryOptions.defaultToSpeaker)
}
catch {
// hard to imagine how we'll get this exception
let alertController = UIAlertController(title: "Speaker Problem", message: "You may be able to hear sound using headphones.", preferredStyle: UIAlertController.Style.alert)
let okAction = UIAlertAction(title: "OK", style: UIAlertAction.Style.default) {
(result: UIAlertAction) -> Void in
}
alertController.addAction(okAction)
self.present(alertController, animated: true, completion: nil)
}
}
}
For this layout, I think FrameLayout is preferred over AutoLayout.
When the viewDidLayoutSubviews method is called, you calculate and update the view size and position according to the screen size.
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
let screenSize = UIScreen.main.bounds
// ...
d4View.frame = ...
}

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.

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
}

Prioritizing iAd over adMob SpriteKit / 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