Show Interstitial In Other Scenes - Admob, SpriteKit, Swift - ios

How do I show an interstitial ad from admob every x times the user has died or every x times the user does something like presses a button? This is how I showed an interstitial ad on my GameScene and limited ad impressions with a simple if statement.

This will only work if you have the GoogleMobileAds.sdk and have imported the googlemobileads module into your GameViewController, and GameScene, OR GameOverScene.
I'll be showing you cross-scene ad implementation and programmatically limiting ad impressions.
First, in your GameViewController:
import GoogleMobileAds
class GameViewController: UIViewController, GADInterstitialDelegate {
var myAd = GADInterstitial()
override func viewDidLoad() {
super.viewDidLoad()
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(GameViewController.loadAndShow), name: "loadAndShow", object: nil)
}
Create two functions at the bottom of your GameViewController:
func loadAndShow() {
myAd = GADInterstitial()
let request = GADRequest()
myAd.setAdUnitID("ca-app-pub-3940256099942544/4411468910")
myAd.delegate = self
myAd.loadRequest(request)
}
func interstitialDidReceiveAd(ad: GADInterstitial!) {
if (self.myAd.isReady) {
myAd.presentFromRootViewController(self)
}
}
You are done with GameViewController. Now head to GameOverScene or GameScene, whatever you need.
Create a global int variable:
var playCount = Int()
In your DidMoveToView say:
playCount = 1
This part is sort of confusing, kinda, not really. Go to your touchesBegan and find where you add actions to a button if it's pressed. For example, a resetGame button resets the scene. Add this there and increment the playButton Int like so:
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
for touch in touches{
let location = touch.locationInNode(self)
if resetGame.containsPoint(location) {
restartScene()
playCount += 1
}
Last step. Add these two functions to the bottom of the scene you want to show interstitial ads in:
func displayAd() {
NSNotificationCenter.defaultCenter().postNotificationName("loadAndShow", object: nil)
}
func checkAd() {
if playCount % 4 == 0 {
displayAd()
}
}
}
Now every fourth time that the user presses the reset game button or dies, an interstitial ad should show up. I hope this helps.
EDIT: I forgot to tell you to call the checkAd() function. Call this function wherever your players dies. So if you have a Bool variable called died or gameover call it in the same spot. For example..
if died == true {
checkAd()
}

import UIKit
import SpriteKit
import GoogleMobileAds
var playCount = Int()
class GameViewController: UIViewController, GADBannerViewDelegate {
#IBOutlet var banner: GADBannerView!
var myAd = GADInterstitial()
override func viewDidLoad() {
super.viewDidLoad()
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(GameViewController.loadAndShow), name: "loadAndShow", object: nil)
let scene = MainScene(size: CGSize(width: 1536, height: 2048))
// Configure the view.
let skView = self.view as! SKView
skView.showsFPS = false
skView.showsNodeCount = false
/* Sprite Kit applies additional optimizations to improve rendering performance */
skView.ignoresSiblingOrder = true
/* Set the scale mode to scale to fit the window */
scene.scaleMode = .AspectFill
skView.presentScene(scene)
banner.hidden = true
banner.delegate = self
banner.adUnitID = "ca-app-pub-8889875503423788/7902691359"
banner.rootViewController = self
banner.loadRequest(GADRequest())
}
func loadAndShow() {
myAd = GADInterstitial()
let request = GADRequest()
myAd.setAdUnitID("ca-app-pub-8889875503423788/7902691359")
myAd.delegate = self
myAd.loadRequest(request)
}
func interstitialDidReceiveAd(ad: GADInterstitial!) {
if (self.myAd.isReady) {
myAd.presentFromRootViewController(self)
}
}
func adViewDidReceiveAd(bannerView: GADBannerView!) {
banner.hidden = false
}
func adView(bannerView: GADBannerView!, didFailToReceiveAdWithError error: GADRequestError!) {
banner.hidden = true
}
override func shouldAutorotate() -> Bool {
return true
}
override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
if UIDevice.currentDevice().userInterfaceIdiom == .Phone {
return .AllButUpsideDown
} else {
return .All
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Release any cached data, images, etc that aren't in use.
}
override func prefersStatusBarHidden() -> Bool {
return true
}
}

Related

Multiple view controllers with different orientations

Explanation
I have a game that runs in landscape, and I'm trying to send an email, also, in portrait mode.
Basically:
if the actual view is GameViewController = .Landscape;
if the actual view is MailViewController = .AllButUpsideDown.
Demo code
I built this code below, but I'm having an issue with it:
Mail isn't being called when touching the screen.
You can download this code here.
GameScene
import SpriteKit
class GameScene: SKScene {
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
/* Called when a touch begins */
//Mail
NSNotificationCenter.defaultCenter().postNotificationName("openMail", object: nil)
}
}
GameViewController
import UIKit
import SpriteKit
class GameViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Set view size.
let scene = GameScene(size: view.bounds.size)
// Configure the view.
let skView = view as! SKView
skView.showsFPS = true
skView.showsNodeCount = true
/* Sprite Kit applies additional optimizations to improve rendering performance */
skView.ignoresSiblingOrder = true
/* Set the scale mode to scale to fit the window */
scene.scaleMode = .ResizeFill
skView.presentScene(scene)
}
override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
if UIDevice.currentDevice().userInterfaceIdiom == .Phone {
return .Landscape
} else {
return .Landscape
}
}
}
MailViewController
import UIKit
import SpriteKit
import MessageUI
class MailViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
//Register mail observer (so I can call from GameScene)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(MailViewController.openMailController), name: "openMail", object: nil)
}
override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
if UIDevice.currentDevice().userInterfaceIdiom == .Phone {
return .AllButUpsideDown
} else {
return .All
}
}
}
//Mail
extension MailViewController: MFMailComposeViewControllerDelegate {
func openMailController() {
let mailComposerVC = MFMailComposeViewController()
mailComposerVC.mailComposeDelegate = self //extremely important to set the mailComposeDelegate property, not the delegate property
self.presentViewController(mailComposerVC, animated: true, completion: nil)
}
func mailComposeController(controller: MFMailComposeViewController, didFinishWithResult result: MFMailComposeResult, error: NSError?) {
self.dismissViewControllerAnimated(true, completion: nil)
}
}
Thanks for any help,
Luiz.
Problem with your provided code is that observer in MailViewController class view did load method is not called. So Observer is not set to receive any notification.
Also you didn't called segue anywhere in your code to call MailViewController.
Solution: By using Delegate Method
GameScene class updated:
import SpriteKit
// Protocol
protocol gameSceneDelegate {
func openMail()
}
// Protocol
class GameScene: SKScene {
// Delegate
var sceneDelegate : gameSceneDelegate?
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
/* Called when a touch begins */
//Mail
// NSNotificationCenter.defaultCenter().postNotificationName("openMail", object: nil)
// delegate method called on receiving touches
self.sceneDelegate?.openMail()
}
}
GameViewController class updated:
import UIKit
import SpriteKit
class GameViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Set view size.
let scene = GameScene(size: view.bounds.size)
// Delegate Confirmation
scene.sceneDelegate = self
// Configure the view.
let skView = view as! SKView
skView.showsFPS = true
skView.showsNodeCount = true
/* Sprite Kit applies additional optimizations to improve rendering performance */
skView.ignoresSiblingOrder = true
/* Set the scale mode to scale to fit the window */
scene.scaleMode = .ResizeFill
skView.presentScene(scene)
}
override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
if UIDevice.currentDevice().userInterfaceIdiom == .Phone {
return .Landscape
} else {
return .Landscape
}
}
}
// Delegate Method Implementation
extension GameViewController : gameSceneDelegate{
func openMail(){
self.performSegueWithIdentifier("openMail", sender: self);
}
}
Mail View Controller:
import UIKit
import SpriteKit
import MessageUI
class MailViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
//Register mail observer (so I can call from GameScene)
// NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(MailViewController.openMailController), name: "openMail", object: nil)
self.openMailController()
}
override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
if UIDevice.currentDevice().userInterfaceIdiom == .Phone {
return .AllButUpsideDown
} else {
return .All
}
}
}
//Mail
extension MailViewController: MFMailComposeViewControllerDelegate {
func openMailController() {
let mailComposerVC = MFMailComposeViewController()
mailComposerVC.mailComposeDelegate = self //extremely important to set the mailComposeDelegate property, not the delegate property
self.presentViewController(mailComposerVC, animated: true, completion: nil)
}
func mailComposeController(controller: MFMailComposeViewController, didFinishWithResult result: MFMailComposeResult, error: NSError?) {
self.dismissViewControllerAnimated(true, completion: nil)
}
}
Last change in storyboard:
click segue connecting GameViewController and MailViewController and change identifier to - openMail or whatever you want to keep

Is there something wrong is my iAd code?

My app was approved just a couple of days ago and had an iAd banner on the bottom of the screen. I know that there it can take up to a week for ads to start appearing, but while I'm waiting.. can someone make sure that I don't have any errors in my code?
import UIKit
import SpriteKit
import iAd
import GameKit
class GameViewController: UIViewController, ADBannerViewDelegate, GKLocalPlayerListener {
var adBanner: ADBannerView!
override func viewDidLoad() {
super.viewDidLoad()
authenticateLocalPlayer()
if let scene = GameScene(fileNamed:"GameScene") {
// Configure the view.
let skView = self.view as! SKView
skView.ignoresSiblingOrder = true
scene.scaleMode = .AspectFill
skView.presentScene(scene)
}
}
func loadBanner() {
adBanner = ADBannerView(frame: CGRect.zero)
adBanner.center = CGPoint(x: adBanner.center.x, y: view.bounds.size.height - adBanner.frame.size.height / 2)
adBanner.delegate = self
adBanner.hidden = true
view.addSubview(adBanner)
}
func bannerViewDidLoadAd(banner: ADBannerView!) {
adBanner.hidden = false
}
func bannerView(banner: ADBannerView!, didFailToReceiveAdWithError error: NSError!) {
adBanner.hidden = true
}
func bannerViewActionShouldBegin(banner: ADBannerView!, willLeaveApplication willLeave: Bool) -> Bool {
return true
}
override func shouldAutorotate() -> Bool {
return true
}
override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
if UIDevice.currentDevice().userInterfaceIdiom == .Phone {
return .AllButUpsideDown
} else {
return .All
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Release any cached data, images, etc that aren't in use.
}
override func prefersStatusBarHidden() -> Bool {
return true
}
func authenticateLocalPlayer() {
let localPlayer = GKLocalPlayer.localPlayer()
localPlayer.authenticateHandler = {(viewController, error) -> Void in
if (viewController != nil) {
self.presentViewController(viewController!, animated: true, completion: nil)
}
else {
print((GKLocalPlayer.localPlayer().authenticated))
}
}
}
}
Right now it just displays a white rectangle. Is there anything wrong with my code, or do I just need to keep waiting for my app to start receiving ads?
iAd is officially discontinued as of tomorrow (June 30th, 2016). I am unsure of the "sign up" process now, but I believe Apple stopped registering apps to receive ads from their network some months ago
Who calls the loadBanner()?
You might consider overriding viewDidAppear() and shifting the code there.

iCarousel in Sprite Kit

Explanation
I'm trying to build a character selection menu similar to Crossy Road's one (as you can see here). So I found this iCarousel, which would help me with all of it, but everything I read talk about implementing it to a ViewController, which isn't my case. I'm using GameScene and I didn't found anything talking about it. Is there anyway I could implement it to my game? or even another effect similar to the character selection menu I mentioned above?
Attempt (beyowulf)
You can download it here.
GameScene.swift
import SpriteKit
class GameScene: SKScene {
var show = SKSpriteNode()
var hide = SKSpriteNode()
func showCharPicker(){
NSNotificationCenter.defaultCenter().postNotificationName("showCharPicker", object: nil)
}
func hideCharPicker(){
NSNotificationCenter.defaultCenter().postNotificationName("hideCharPicker", object: nil)
}
override func didMoveToView(view: SKView) {
/* Setup your scene here */
print("didMoveToView")
show = SKSpriteNode(imageNamed: "show")
show.anchorPoint = CGPointZero
show.position = CGPointZero
addChild(show)
hide = SKSpriteNode(imageNamed: "hide")
hide.anchorPoint = CGPointZero
hide.position = CGPoint(x: self.frame.width / 2 - hide.frame.width / 2, y: 0)
addChild(hide)
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
for touch in touches{
let location = touch.locationInNode(self)
let node = nodeAtPoint(location)
if node == show{
print("show")
showCharPicker()
}
else if node == hide{
print("hide")
hideCharPicker()
}
}
}
}
GameViewController.swift
import UIKit
import SpriteKit
class GameViewController: UIViewController, iCarouselDataSource, iCarouselDelegate{
var squaresArray : NSMutableArray = NSMutableArray()
#IBOutlet weak var carousel: iCarousel!
deinit{
NSNotificationCenter.defaultCenter().removeObserver(self)
}
func showCarousel(){
self.carousel.hidden = false
}
func hideCarousel(){
self.carousel.hidden = true
}
override func viewDidLoad(){
super.viewDidLoad()
// Configure iCarousel
carousel.dataSource = self
carousel.delegate = self
carousel.type = .CoverFlow
carousel.reloadData()
self.carousel.hidden = true
// Register showCarousel and hideCarousel functions
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.showCarousel), name: "showCharPicker", object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.hideCarousel), name: "hideCharPicker", object: nil)
// Configure view
let skView = SKView()
self.view.insertSubview(skView, belowSubview: self.carousel)
skView.frame = self.view.bounds
// Additionals
skView.showsFPS = true
skView.showsNodeCount = true
skView.ignoresSiblingOrder = true
// Configure scene
let scene = GameScene(size:self.view.bounds.size)
scene.scaleMode = .ResizeFill
scene.size = self.view.bounds.size
skView.presentScene(scene)
}
//iCarousel
override func awakeFromNib(){
super.awakeFromNib()
squaresArray = NSMutableArray(array: ["square1","square2","square3"])
}
func numberOfItemsInCarousel(carousel: iCarousel) -> Int{
return squaresArray.count
}
func carousel(carousel:iCarousel, didSelectItemAtIndex index:NSInteger){
//self.hideCarousel()
}
func carousel(carousel: iCarousel, viewForItemAtIndex index: Int, reusingView view: UIView?) -> UIView{
var itemView: UIImageView
if (view == nil){
itemView = UIImageView(frame:CGRect(x:0, y:0, width:200, height:200))
itemView.contentMode = .Center
}
else{
itemView = view as! UIImageView;
}
itemView.image = UIImage(named: "\(squaresArray.objectAtIndex(index))")
return itemView
}
func carousel(carousel: iCarousel, valueForOption option: iCarouselOption, withDefault value: CGFloat) -> CGFloat{
if (option == .Spacing){
return value * 2
}
return value
}
}
What's happening:
Thanks in advance,
Luiz.
You can use NSNotifications to show your character picker. You just need to observe the notifications posted by your SKScene. Your viewDidLoad should look something like:
override func viewDidLoad(){
super.viewDidLoad()
carousel.type = .CoverFlow
carousel.reloadData()
let spriteKitView = SKView()
spriteKitView.frame = self.view.bounds
self.view.insertSubview(spriteKitView, belowSubview: self.carousel)
spriteKitView.showsFPS = true
spriteKitView.showsNodeCount = true
spriteKitView.ignoresSiblingOrder = true
self.gameScene = GameScene(size:self.view.bounds.size)
self.gameScene.scaleMode = .AspectFill
self.gameScene.imageName = self.images[0] as! String
self.carousel.hidden = true
spriteKitView.presentScene(self.gameScene)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.showCarousel), name: gameScene.kShowNotification, object: nil)
}
You'll want to implementing carousel(carousel:iCarousel, didSelectItemAtIndex index:NSInteger) so you know what is selected, and so you can return to game play. For example:
func carousel(carousel:iCarousel, didSelectItemAtIndex index:NSInteger)
{
self.gameScene.imageName = self.images[index] as! String
self.hideCarousel()
}
You also need to remove observing before your view controller is deallocated.
deinit
{
NSNotificationCenter.defaultCenter().removeObserver(self)
}
Your SKScene can then post a notifications:
import SpriteKit
class GameScene: SKScene {
var imageName = "square1"{
didSet{
self.hidden = false
self.childNode.texture = SKTexture(imageNamed: imageName)
}
}
let kShowNotification = "showPicker"
var childNode = SKSpriteNode()
override func didMoveToView(view: SKView) {
/* Setup your scene here */
self.childNode = SKSpriteNode(imageNamed: imageName)
self.childNode.anchorPoint = CGPointZero
self.childNode.position = CGPointZero
self.addChild(self.childNode)
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
self.showCharPicker()
}
func showCharPicker()
{
self.hidden = true
NSNotificationCenter.defaultCenter().postNotificationName(kShowNotification, object: nil)
}
}
If you want to change hit detection, you need to subclass the view for which you need it to change. This case your iCarousel view.
You can then either override hitTest or pointInside. I've created an iCarousel subclass and overrode pointInside to only return true when the point is inside one of the carousel's contentView's subviews.
class CarouselSubclass: iCarousel {
override func pointInside(point: CGPoint, withEvent event: UIEvent?) -> Bool {
var inside = false
for view in self.contentView.subviews
{
inside = CGRectContainsPoint(view.frame, point)
if inside
{
return inside
}
}
return inside
}
}
You need to remember to change the class of your carousel in interface builder and update your outlet as well.

Swift SpriteKit: iAd loading bug

I currently have a bug with the app I am working on where when a user taps on an iAd banner and the ad loads, the game resets. By "resets" I mean all their progression (other than the NSUserDefaults data) is reset to 0 and the scene is reset back to the start of the game.
My game primary runs from didMoveToView() and touchesBegan(). In my GameViewController the game scene is built from viewWillLayoutSubviews().
Here is how I control my ads and placement. Not sure if has to do with the placement of my code or the ad.
import UIKit
import SpriteKit
import iAd
// Global Ad Variable
var adBanner: ADBannerView!
class GameViewController: UIViewController, ADBannerViewDelegate {
/* Load Ads */
func loadAds() {
adBanner = ADBannerView(frame: CGRect(x: 0, y: view.bounds.size.height - 50, width: 320, height: 50))
adBanner.delegate = self
adBanner.hidden = true
self.view.addSubview(adBanner)
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
if let scene = GameScene(fileNamed:"GameScene") {
// Configure the view.
let skView = self.view as! SKView
// Create and Configure the scene
scene.size = skView.bounds.size
skView.showsFPS = false // SHOW OR HIDE FRAMES PER SECOND
skView.showsNodeCount = false
/* Sprite Kit applies additional optimizations to improve rendering performance */
skView.ignoresSiblingOrder = true
/* Set the scale mode to scale to fit the window */
scene.scaleMode = .AspectFill
skView.presentScene(scene)
}
}
override func awakeFromNib() {
super.awakeFromNib()
loadAds()
}
override func shouldAutorotate() -> Bool {
return true
}
override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
if UIDevice.currentDevice().userInterfaceIdiom == .Phone {
return .AllButUpsideDown
} else {
return .All
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Release any cached data, images, etc that aren't in use.
}
override func prefersStatusBarHidden() -> Bool {
return true
}
func bannerView(banner: ADBannerView!, didFailToReceiveAdWithError error: NSError!) {
adBanner.hidden = true
print("There was an error loading ad")
}
func bannerViewWillLoadAd(banner: ADBannerView!) {
print("Ad Loading")
}
func bannerViewDidLoadAd(banner: ADBannerView!) {
adBanner.hidden = false
print("Ad Loaded")
}
}

iAd didFailToReceiveAdWithError not working sometimes, displays white box

I'm using Swift and SpriteKit, and everything is made inside my GameViewController and GameScene.
This is all code concerning the ads inside my GameViewController:
class GameViewController: UIViewController, ADBannerViewDelegate, GADBannerViewDelegate {
var adBannerView: ADBannerView!
var gadBannerView: GADBannerView!
var bannerDisplayed = false
var bannerNow = "iAd"
override func viewDidLoad() {
super.viewDidLoad()
if let scene = GameScene.unarchiveFromFile("GameScene") as? GameScene {
// Configure the view.
let skView = self.view as! SKView
skView.showsFPS = false
skView.showsNodeCount = false
/* Sprite Kit applies additional optimizations to improve rendering performance */
skView.ignoresSiblingOrder = true
/* Set the scale mode to scale to fit the window */
scene.scaleMode = .AspectFill
if((UIDevice.currentDevice().userInterfaceIdiom == .Phone) && (UIScreen.mainScreen().bounds.height <= 480)) {
println("<= iPhone 4S")
scene.size.height = skView.bounds.size.height * 2
scene.size.width = skView.bounds.size.width * 2
}
NSNotificationCenter.defaultCenter().addObserver(self, selector: "hideADBanner", name: "hideAd", object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "showADBanner", name: "showAd", object: nil)
self.adBannerView = self.loadAds()
skView.presentScene(scene)
println(gadBannerView)
}
}
func loadAds()->ADBannerView{
var adBannerView2 = ADBannerView(frame: CGRect.zeroRect)
adBannerView2.center = CGPoint(x: adBannerView2.center.x, y: view!.bounds.size.height - adBannerView2.frame.size.height / 2)
adBannerView2.delegate = self
adBannerView2.hidden = true
bannerNow = "iAd"
self.view?.addSubview(adBannerView2)
return adBannerView2
}
func bannerViewActionShouldBegin(banner: ADBannerView!, willLeaveApplication willLeave: Bool) -> Bool {
println("left for ad")
return true
}
func bannerViewActionDidFinish(banner: ADBannerView!) {
}
func bannerViewDidLoadAd(banner: ADBannerView!) {
println("ad did load.")
println("Delegate: \(adBannerView.delegate)")
adBannerView.hidden = false
//gadBannerView?.removeFromSuperview()
}
func bannerView(banner: ADBannerView!, didFailToReceiveAdWithError error: NSError!) {
//adBannerView.removeFromSuperview()
//self.gadBannerView = self.createGADBanner()
}
func createGADBanner()->GADBannerView {
var ad = GADBannerView()
ad = GADBannerView(frame: CGRectMake(0, 0, self.view.frame.size.width, 50))
ad.delegate = self
ad.rootViewController = self
ad.adUnitID = "xxxxxxxxxxx"
bannerNow = "GAD"
var reqAd = GADRequest()
//reqAd.testDevices = [GAD_SIMULATOR_ID] // If you want test ad's
ad.loadRequest(reqAd)
self.view.addSubview(ad)
println(ad)
return ad
}
func adViewDidReceiveAd(view: GADBannerView!) {
println("adViewDidReceiveAd:\(view)");
bannerDisplayed = true
relayoutViews()
}
func adView(bannerView: GADBannerView!, didFailToReceiveAdWithError error: GADRequestError!) {
gadBannerView.removeFromSuperview()
}
func relayoutViews() {
if (bannerDisplayed) {
var bannerFrame = gadBannerView!.frame
bannerFrame.origin.x = 0
bannerFrame.origin.y = self.view.bounds.size.height - bannerFrame.size.height
gadBannerView!.frame = bannerFrame
}
}
func hideADBanner() {
println(self.gadBannerView)
println(bannerNow)
//adBannerView?.hidden = true
//gadBannerView?.hidden = true
adBannerView?.removeFromSuperview()
gadBannerView?.removeFromSuperview()
}
func showADBanner() {
self.adBannerView = self.loadAds()
//adBannerView?.hidden = false
//gadBannerView?.hidden = false
}
So my plan is to get ads from AdMob when iAd is not working, but the problem is that my iAd "always works", even though I've changed the fill-rate inside the Developer tools in my iPhone.
When iAd loads the ad it works fine, the function bannerViewDidLoadAd() is called and the ad is displayed. Although sometimes when I load iAd it says that I've entered bannerViewDidLoadAd() but it only displays a white "box" with the iAd logo in the bottom. Now, this is not what I want because then AdMob is never gonna show. The println always put out the same delegate so it seems like that works at least.
This view never refreshes because everything, as I said, is handled in the GameScene where it's just removing and adding nodes.
Thank you!
You're over complicating things immensely with bool's, unnecessary functions, and it looks like you've actually created two ADBannerViews once in Interface Builder, self.adBannerView, and once programmatically, var adBannerView: ADBannerView!.
I've created an example with comments to help you along the way. Whats happening here is we are creating an ADBannerView, setting it up once in our viewDidLoad, and then hiding/showing our ADBannerView depending on if it receives an ad from the iAd network or not. I've left out the AdMob implementation as it should be pretty straight forward now.
import UIKit
import iAd // Import iAd
class ViewController: UIViewController, ADBannerViewDelegate { // Include the delegate for our ADBannerView
var adBannerView = ADBannerView() // Create our ADBannerView
// Create your GADBannerView here
override func viewDidLoad() {
super.viewDidLoad()
loadAds()
}
func loadAds() {
// Setup our ADBannerView
adBannerView = ADBannerView(frame: CGRect.zeroRect)
adBannerView.center = CGPoint(x: view.bounds.size.width / 2, y: view.bounds.size.height - adBannerView.frame.size.height / 2)
adBannerView.delegate = self
adBannerView.hidden = true
view.addSubview(adBannerView)
// Setup your GADBannerView here in the same manner
}
func bannerViewDidLoadAd(banner: ADBannerView!) {
println("bannerViewDidLoadAd")
// We received an ad from iAd. Lets show our banner
adBannerView.hidden = false
// Hide your GADBannerView here
}
func bannerViewActionDidFinish(banner: ADBannerView!) {
println("bannerViewActionDidFinish")
}
func bannerView(banner: ADBannerView!, didFailToReceiveAdWithError error: NSError!) {
println("didFailToReceiveAdWithError: \(error)")
// We failed to receive an ad from iAd. Lets hide our banner and print the error
adBannerView.hidden = true
// Show your GADBannerView here
}

Resources