Admob banner for app with iPad Multitasking / Split View enabled (Swift) - ios

I am making an app for iPad with multitasking enabled and right now I am trying to implement an Admob banner.
There is an article about doing that in case of multitasking enabled (https://developers.google.com/admob/ios/multiscene?hl=ru) but all code there is written in Objective-C when I'm using Swift.
I tried to translate it but I have no idea how to do that for the piece of code below. What is "requestInitialized"? What it should do and how to write it in Swift?
If anyone has a full code for successful implementing an Admob banner in multitasking app, please help me with it
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
if (!_requestInitialized) {
[self loadInterstitial];
_requestInitialized = YES;
}
}

For SwiftUI you can add this :
request.scene = UIApplication.shared.connectedScenes.first as? UIWindowScene

GoogleAdmob does offer a quick-start here that does show you Swift.. I will also provide some instructions.
Make sure you have the GoogleMobileAds pod added to your project and have the correct plist setup.
In your didFinishLaunchingWithOptions in your AppDelegate.swift add the following:
GADMobileAds.sharedInstance().start(completionHandler: nil)
Drag and drop a normal UIView into your storyboard, give it a width of 320 and a height of 50. Then you can change the class of the view to a GADBannerView. Then use the code below and make sure your IBOutlet is connected.
import UIKit
import GoogleMobileAds
class ViewController: UIViewController, GADBannerViewDelegate {
#IBOutlet weak var bannerView: GADBannerView!
override func viewDidLoad() {
super.viewDidLoad()
bannerView.adUnitID = "ca-app-pub-3940256099942544/6300978111" // Test Banner ID, replace with your ID here.
bannerView.rootViewController = self
bannerView.load(GADRequest())
bannerView.delegate = self
}
// MARK: - GADBannerViewDelegate
func adViewDidReceiveAd(_ bannerView: GADBannerView) {
print("Received Ad")
}
func adView(_ bannerView: GADBannerView, didFailToReceiveAdWithError error: GADRequestError) {
print(error)
}
}

Related

UIKit ViewController ===> into SwiftUI ContentView

Trying to integrate Facebook audience Network ad placements into my SwiftUI project.
The tutorial published by Facebook assumes the use of UIKit only!
With zero experience in UIKit, need your kind help to enable me to integrate the follwing lines of code into my ContentView as a SwiftUI view:
//Add a UIView element to the main View element and name it to adContainer.
//Now, in your View Controller header file (or Swift file, if you are a Swift user),
//import FBAudienceNetwork, declare conformance to the FBAdViewDelegate protocol,
//and add an instance variable for the ad unit
import UIKit
import FBAudienceNetwork
class ViewController: UIViewController, FBAdViewDelegate {
#IBOutlet private var adContainer: UIView!
private var adView: FBAdView?
}
//Add the code below to viewDidLoad; Create a new instance of FBAdView and add it to the view.
//FBAdView is a subclass of UIView. You can add it to your view hierarchy just like any other view.
override func viewDidLoad() {
super.viewDidLoad()
// Instantiate an AdView object.
// NOTE: the placement ID will eventually identify this as your app, you can ignore while you
// are testing and replace it later when you have signed up.
// While you are using this temporary code you will only get test ads and if you release
// your code like this to the App Store your users will not receive ads (you will get a 'No Fill' error).
let adView = FBAdView(placementID: "YOUR_PLACEMENT_ID", adSize: kFBAdSizeHeight50Banner, rootViewController: self)
adView.frame = CGRect(x: 0, y: 0, width: 320, height: 250)
adView.delegate = self
adView.loadAd()
self.adView = adView
}
//Optionally, you can add the following functions to handle the cases
//where the ad is closed or when the user clicks on it:
func adViewDidClick(_ adView: FBAdView) {
print("Ad was clicked.")
}
func adViewDidFinishHandlingClick(_ adView: FBAdView) {
print("Ad did finish click handling.")
}
func adViewWillLogImpression(_ adView: FBAdView) {
print("Ad impression is being captured.")
}
//Add and implement the following two delegate functions in your
//View Controller to handle ad loading failures:
func adView(_ adView: FBAdView, didFailWithError error: Error) {
print("Ad failed to load with error: \(error.localizedDescription)")
}
func adViewDidLoad(_ adView: FBAdView) {
print("Ad was loaded and ready to be displayed")
showAd()
}
private func showAd() {
guard let adView = adView, adView.isAdValid else {
return
}
adContainer.addSubview(adView)
}
Your help would be tremendously appreciated would be

How to create a shared Admob banner for multiple views?

I am buildung my very first application with Admob banners in Xcode.
My apps uses multiple UIViews connect via NavigationController and currently I am requesting a new ad for every UIView.
That is what I already got for every UIViewController:
import GoogleMobileAds
class ViewController: UIViewController {
#IBOutlet weak var bannerView: GADBannerView!
override func viewDidLoad() {
super.viewDidLoad()
bannerView.adUnitID = "ca-app-pub-281379xxxxx/64134xxxxx"
bannerView.rootViewController = self
bannerView.loadRequest(GADRequest())
}
}
How can I implement a "shared" banner for all views which gets managed from a separate class or by the AppDelegate. (All of my views got an GADBannerView at the bottom already.)
I never really worked with delegate methods before, because coding is just hobby from me and I am learning like: Try & Error. But at this point my skills aren't good enough to realize this.
I would appreciate any kind of help :-). Thank you!

How to implement Google AdMobs banner ad in swift?

I want to add an banner advertisement in my tabbed app but I am not able to do it.
How exactly can I implement banner adds?
This is what I have tried-
import UIKit
import GoogleMobileAds
class ViewController: UIViewController {
var banner : GADBannerView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
loadBanner()
}
func loadBanner(){
banner = GADBannerView(adSize: kGADAdSizeSmartBannerPortrait)
banner.adUnitID = "my_app_id"
banner.rootViewController = self
let req : GADRequest = GADRequest()
banner.loadRequest(req)
banner.frame = CGRectMake(0, view.bounds.height - banner.frame.size.height, banner.frame.size.width, banner.frame.size.height)
self.view.addSubview(banner)
}
If you want to test the Admob Integration you have to specify testDevices in the GADRequest object like this:
var request = GADRequest()
request.testDevices = [GAD_SIMULATOR_ID];
In the testDevices array you can put also the UUIDs of the phones you are testing on.
Also, did you do the steps from here? They are different things.
You should make the following call in didFinishLaunchingWithOptionsMethod:
GADMobileAds.configureWithApplicationID("YOUR_APPLICATION_ID");
Don't mistake the APPLICATION_ID with AD_UNIT_ID!

Placing iAd and Admob banner is causing an issue

I've been trying to do the following with iAd and Admob banner:
First i placed iAd over Admob banner in storyboard and I've added all the needed constraints, if iAd fail to receive i will show Admob banner if i received iAd i am gonna hide Admob and then show iAd banner..etc.
The issue doesn't happen all the time, while admob banner is showing iAd comes and push the admob banner to the top without hiding it. but in the code it should hide it.this issue happens after hiding and showing, hiding and showing many times..
Please check the following screenshot.
ViewController code:
#IBOutlet weak var Gbanner: GADBannerView!
#IBOutlet weak var AbannerView: ADBannerView!
override func viewDidLoad() {
super.viewDidLoad()
AbannerView.delegate = self
self.canDisplayBannerAds = true
showadmob()
// Do any additional setup after loading the view, typically from a nib.
}
func bannerView(banner: ADBannerView!, didFailToReceiveAdWithError error: NSError!) {
println("didFailToReceiveAdWithError")
AbannerView.hidden = true
Gbanner.hidden = false
}
func bannerViewActionDidFinish(banner: ADBannerView!) {
println("bannerViewActionDidFinish")
}
func bannerViewDidLoadAd(banner: ADBannerView!) {
println("bannerViewDidLoadAd")
Gbanner.hidden = true
AbannerView.hidden = false
}
func bannerViewWillLoadAd(banner: ADBannerView!) {
println("bannerViewWillLoadAd")
}
func showadmob(){
self.Gbanner.adUnitID = "somethingelsehere"
self.Gbanner.rootViewController = self
var request: GADRequest = GADRequest()
self.Gbanner.loadRequest(request)
}
Download project here : https://yadi.sk/d/1VcjfJG9ixNZg
If you're implementing your own ADBannerView then you need to remove self.canDisplayBannerAds = true from your viewDidLoad.
self.canDisplayBannerAds = true can be used for a no hassle way of implementing iAd banners in your application. This will create an ADBannerView for you and show or hide the ADBannerView depending on whether it receives an ad or not from the iAd network.
You either implement your own ADBannerView or use self.canDisplayBannerAds = true, not both.

How to call admob interstitial ad using swift, spritekit and xcode?

I've been looking all over for an answer to this and I've found lots of examples in objective C (google developer docs, etc.) and some answers in swift, but not using spritekit, and being a novice, I just haven't been able to bridge the gaps in these tutorials to put it all together for my project. Honestly, I don't really care if the ad is called on app launch, or game over, I'd just be happy being able to call the ad period, though I guess on game launch is preferred.
Pretty sure I've got it all set up correctly in gameviewcontroller.swift, but I don't know how to actually call it. Here is the code from my gameviewcontroller.swift:
import UIKit
import SpriteKit
import GoogleMobileAds
class GameViewController: UIViewController {
var interstitial : GADInterstitial!
func createAndLoadAd() -> GADInterstitial {
var ad = GADInterstitial()
ad.adUnitID = "ca-app-pub-4471013071748494/2980967718"
var request = GADRequest()
request.testDevices = [""]
return ad
}
Beyond this ... I also have this if statement to call the ad, but I don't know where it should be ... or if it's complete (in the tutorial, it was in a button, but I need it to be automatic, naturally:
if (self.interstitial.isReady) {
self.interstitial.presentFromRootViewController(self)
self.interstitial = self.createAndLoadAd()
}
Anyone have any experience with this? If anyone could help me complete this by letting me know where to place that above if statement, or if there is more that needs to be done ... your help will be much appreciated. Thank you.
Ok so I started a new project (Swift project) which is Game Project
In GameViewController:
class GameViewController: UIViewController
{
var interstitial = GADInterstitial()
override func viewDidLoad()
{
super.viewDidLoad()
if let scene = GameScene.unarchiveFromFile("GameScene") as? GameScene
{
// Configure the view.
let skView = self.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 = .AspectFill
skView.presentScene(scene)
let delayTime = dispatch_time(DISPATCH_TIME_NOW,
Int64(5 * Double(NSEC_PER_SEC)))
//Creation of the ad and its request
self.interstitial = GADInterstitial()
self.interstitial.adUnitID = "ca-app-pub-4798156420380453/7714267723"
var request = GADRequest()
// request.testDevices = [""]
self.interstitial.loadRequest(GADRequest());//The method u were missing
dispatch_after(delayTime, dispatch_get_main_queue())
{
self.showAd()
}
}
}
func showAd()
{
if (self.interstitial.isReady)
{
self.interstitial.presentFromRootViewController(self)//Whatever shows the ad
}
}
It is my first swift code so don't judge me if I did something wrong
But when I lunch it after ±5 seconds i see the ad
Here is your example.
I am not familiar with Swift at all ,
but all you need to do is to get the interstitial delegate when it dismissed -> and request for the next interstitial, So in next time you will get the new AD
Feel free to ask anything !
P.S. Don't forget to change the admob ID to your ID.
My solution based on above comments was the following:
1) Add this in the GameViewController.swift
protocol AdmobInterstitialDelegate{
func showInterstitial()
}
...
// add this delegate in GameViewController definition
class GameViewController: UIViewController, GADInterstitialDelegate, AdmobInterstitialDelegate {
...
// and assign it to the GameScene class when you create its instance
let scene = GameScene()
scene.adDelegate = self
// do not forget to implement the delegated method itself
func showInterstitial(){
if (interstitial!.isReady) {
interstitial!.presentFromRootViewController(self)
}
}
and then you can use it in GameScene
class GameScene: SKScene {
....
var adDelegate: AdmobInterstitialDelegate?
....
// and finally - show the ad
override func didMoveToView(view: SKView) {
self.adDelegate?.showInterstitial();
....
hope this helps.
keep the if condition in viewDidAppear it will automatically execute
override func viewDidAppear(animated: Bool) {
if (interstitial.isReady) {
interstitial.presentFromRootViewController(self)
self.interstitial = self.createAndLoadInterstitial()
}

Resources