Shared iAd banner - ios

I am making the iAds in my app to be loaded in the app delegate. It loads fine however in the view controllers, it will not show.
My code in the app delegate to declare the ad is
var UIiAd: ADBannerView = ADBannerView()
My code in the view controller is
class HelpViewController: UIViewController, ADBannerViewDelegate {
//MARK: - Properties
var UIiAd: ADBannerView = ADBannerView()
//MARK: - did something
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func viewWillAppear(animated: Bool) {
//super.viewWillAppear(animated)
let ScreenHeight = UIScreen.mainScreen().bounds.height
UIiAd.delegate = self
UIiAd = self.appDelegate().UIiAd
UIiAd.frame = CGRectMake(0, ScreenHeight - 50, 0, 0)
UIiAd.hidden = true
self.view.addSubview(UIiAd)
}
override func viewWillDisappear(animated: Bool) {
UIiAd.delegate = nil
UIiAd.removeFromSuperview()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//MARK: - iAd
func bannerViewDidLoadAd(banner: ADBannerView!) {
UIView.beginAnimations(nil, context: nil)
UIView.setAnimationDuration(1)
UIiAd.hidden = false
UIView.commitAnimations()
print("Did load ad")
}
func bannerView(banner: ADBannerView!, didFailToReceiveAdWithError error: NSError!) {
UIView.beginAnimations(nil, context: nil)
UIView.setAnimationDuration(0)
UIiAd.hidden = true
UIView.commitAnimations()
print("Did fail to receive ad with error \(error)")
}
//MARK: - Functions
func appDelegate() -> AppDelegate {
return UIApplication.sharedApplication().delegate as! AppDelegate
}
}
What seems to be the problem is, bannerViewDidLoadAd doesn't ever get called. How would I unhide the banner if it loads?

I have actually fixed this. What you need to do in the app delegate is
class AppDelegate: UIResponder, UIApplicationDelegate, ADBannerViewDelegate
Then you want to make a bool that changes if the ad is loaded
Then you want to add the function func bannerViewDidLoadAd(banner: ADBannerView!) {
adLoaded = true
}
This will change the value when the ad is loaded
Then in your view controller you want to do
override func viewWillAppear(animated: Bool) {
//super.viewWillAppear(animated)
let ScreenHeight = UIScreen.mainScreen().bounds.height
UIiAd.delegate = self
UIiAd = self.appDelegate().UIiAd
UIiAd.frame = CGRectMake(0, ScreenHeight - 50, 0, 0)
canDisplayBannerAds = true
if appDelegate().adLoaded == true {
self.view.addSubview(UIiAd)
}
}
This will add the ad to your view controller will not if the ad is not loaded

Related

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.

Controller does not resize the views when ADBannerView added

Reading through Apple's documentation on iAD I got the impression, that if I'll add the ADBannerView to my controller's view tree - other views will be scaled to fit the add. But apparently that's not the case as you can see here :
That's the code I'm using :
import UIKit
import SpriteKit
import iAd
class GameViewController: UIViewController, ADBannerViewDelegate {
var mainView: SKView!
let adBanner = ADBannerView(adType: .Banner)
override func viewDidLoad() {
super.viewDidLoad()
mainView = self.view as? SKView
mainView.showsDrawCount = true
mainView.showsNodeCount = true
mainView.showsFPS = true
adBanner.delegate = self
adBanner.center = CGPoint(x: adBanner.center.x, y: mainView.bounds.size.height - adBanner.frame.size.height / 2)
adBanner.hidden = true
}
func bannerViewActionShouldBegin(banner: ADBannerView!, willLeaveApplication willLeave: Bool) -> Bool {
return true
}
func bannerView(banner: ADBannerView!, didFailToReceiveAdWithError error: NSError!) {
NSLog("error: \(error)")
}
func bannerViewWillLoadAd(banner: ADBannerView!) {
print("WILL LOAD BANNER")
}
func bannerViewDidLoadAd(banner: ADBannerView!) {
print("Loaded Ad \(banner)")
adBanner.hidden = false
}
override func viewWillAppear(animated: Bool) {
let helloScene = HelloScene(size: mainView.frame.size)
mainView.presentScene(helloScene)
mainView.addSubview(adBanner)
}
override func shouldAutorotate() -> Bool {
return false
}
override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
if UIDevice.currentDevice().userInterfaceIdiom == .Phone {
return UIInterfaceOrientationMask.AllButUpsideDown
} else {
return UIInterfaceOrientationMask.All
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func prefersStatusBarHidden() -> Bool {
return true
}
}
Am I missing something ? If I'll set controller's self.canDisplayBannerAds = true then banner is displayed properly at the bottom with the rest scaled as I would expect.
Is it because I'm using presentScene, which adds SKScene and not a view ?
UPDATE
I've tried adding constraints, but I guess there's a lot of reading ahead of me cause I couldn't yet figure that out :) I googled for a while and came up with this, but that didn't change anything so probably I'm doing it wrong (added that to viewDidLoad :
mainView.addSubview(adBanner)
let viewsDictionary = ["adBanner": adBanner]
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[adBanner]|", options: NSLayoutFormatOptions.AlignAllBaseline, metrics: nil, views: viewsDictionary))
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[adBanner]|", options: NSLayoutFormatOptions.AlignAllBaseline, metrics: nil, views: viewsDictionary))
You can replace your complete code with
self.canDisplayBannerAds = true
Here is a short tutorial.

How to stop an ad banner resizing the frame in Swift

I have almost completed a game for IOS in Swift and am having an issue with my banner. I managed to find some code to stop it resizing the view frame, but now it seems to resize completely randomly; sometimes not resizing (as desired) sometimes resizing as is default.
extension SKNode {
class func unarchiveFromFile(file : String) -> SKNode? {
if let path = NSBundle.mainBundle().pathForResource(file, ofType: "sks") {
var sceneData = NSData(contentsOfFile: path, options: .DataReadingMappedIfSafe, error: nil)!
var archiver = NSKeyedUnarchiver(forReadingWithData: sceneData)
archiver.setClass(self.classForKeyedUnarchiver(), forClassName: "SKScene")
let scene = archiver.decodeObjectForKey(NSKeyedArchiveRootObjectKey) as! GameScene
archiver.finishDecoding()
return scene
} else {
return nil
}
}
}
class GameViewController: UIViewController, ADBannerViewDelegate {
let gameCenterPlayer = GKLocalPlayer.localPlayer()
var bannerView:ADBannerView?
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
NSNotificationCenter.defaultCenter().addObserver(self, selector: "updateNoAds:", name: "noAdsID", object: nil)
skView.presentScene(scene)
}
// disabling ads if no-ads is purchased
if bannerAdsOff != true {
self.canDisplayBannerAds = true
} else {
self.canDisplayBannerAds = false
}
bannerView = ADBannerView()
bannerView?.delegate = self
bannerView?.frame = CGRectZero
bannerView?.backgroundColor = UIColor.clearColor()
bannerView!.frame = CGRectMake(0, self.view.frame.size.height - self.bannerView!.frame.size.height, self.bannerView!.frame.size.width, self.bannerView!.frame.size.height)
bannerView?.hidden = true
view.addSubview(bannerView!)
}
func updateNoAds(notification: NSNotification) {
self.canDisplayBannerAds = false
println("turning can Display banner ads off")
self.bannerView?.hidden = true
println("bannerview hidden = \(self.bannerView?.hidden)")
}
override func shouldAutorotate() -> Bool {
return true
}
override func supportedInterfaceOrientations() -> Int {
if UIDevice.currentDevice().userInterfaceIdiom == .Phone {
return Int(UIInterfaceOrientationMask.AllButUpsideDown.rawValue)
} else {
return Int(UIInterfaceOrientationMask.All.rawValue)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Release any cached data, images, etc that aren't in use.
}
override func prefersStatusBarHidden() -> Bool {
return true
}
func bannerViewDidLoadAd(banner: ADBannerView!) {
if bannerAdsOff != true {
self.bannerView?.hidden = false
}
}
func bannerViewActionShouldBegin(banner: ADBannerView!, willLeaveApplication willLeave: Bool) -> Bool {
return willLeave
}
func bannerView(banner: ADBannerView!, didFailToReceiveAdWithError error: NSError!) {
self.bannerView?.hidden = true
}
}
I have read somewhere that it has to do with the canDisplayBannerAds setting, but if I change that to false, it just means no ads are shown at all.
I'm hoping to release tomorrow and would really like to have this fixed for the release :)
Here is some working code for you that just worked for me. This does not need self.candisplaybannerads = true as I had some issues with that. The ad automatically changes the size according to the screen size and is located at the bottom of the screen. In my spritkit game it did not resize the scene.
import iAd
class viewController: UIViewController, ADBannerViewDelegate {
var AdBanner = ADBannerView()
override func viewDidLoad() {
super.viewDidLoad()
/* Ad Banner Settings */
AdBanner = ADBannerView()
AdBanner.frame = CGRectZero
AdBanner.delegate = self
self.AdBanner.frame = CGRectMake(0, self.view.frame.size.height-self.AdBanner.frame.size.height, self.AdBanner.frame.size.width, self.AdBanner.frame.size.height)
AdBanner.backgroundColor = UIColor.clearColor()
self.view .addSubview(AdBanner)
}
/* All iAd Functions */
func bannerViewActionShouldBegin(banner: ADBannerView!, willLeaveApplication willLeave: Bool) -> Bool {
/* whatever you need */
return true
}
func bannerViewActionDidFinish(banner: ADBannerView!) {
/* whatever you need */
}
func bannerViewDidLoadAd(banner: ADBannerView!) {
AdBanner.hidden = false
}
func bannerView(banner: ADBannerView!, didFailToReceiveAdWithError error: NSError!) {
NSLog("Error Loading Ad")
/* whatever you need */
AdBanner.hidden = true
}
func bannerViewWillLoadAd(banner: ADBannerView!) {
/* whatever you need */
}

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
}

iAd banner problems

The error and the problem:
WARNING: More than 10 instances of ADBannerView or ADInterstitialView currently exist. This is a misuse of the iAd API, and ad performance will suffer as a result. This message is printed only once.
my implementation of the adView:
var adView = ADBannerView()
override func viewDidLoad() {
super.viewDidLoad()
adView.frame = CGRectOffset(adView.frame, 0, self.view.bounds.height - adView.bounds.height)
adView.sizeToFit()
self.view .addSubview(adView)
adView.alpha = 0.001
adView.delegate = self
}
i have looked on the internet and i found that i need to implement the "viewWillDisappear" and i did so:
my first try:
override func viewWillDisappear(animated: Bool) {
adView.removeFromSuperview()
adView.delegate = nil
}
and the second:
override func viewWillDisappear(animated: Bool) {
for view in self.view.subviews {
view.removeFromSuperview()
}
adView.removeFromSuperview()
adView.delegate = nil
}
one more thing, it says that it will just be displayed once but i get the error every time i run the app on my phone
After some search i came to this solution :
let adView = ADBannerView()
override func viewDidLoad() {
super.viewDidLoad()
adView.frame = CGRectOffset(adView.frame, 0, self.view.bounds.height - adView.bounds.height)
adView.sizeToFit()
adView.alpha = 0.001
adView.delegate = self
self.view .addSubview(adView)
self.canDisplayBannerAds = true
}
override func viewWillDisappear(animated: Bool) {
for view in self.view.subviews {
view.removeFromSuperview()
}
adView.hidden = true
adView.delegate = nil
adView.removeFromSuperview()
}
apparently I missed to add the "self.canDisplayBannerAds = true" and that fixed the problem for now

Resources