SwiftでGoogleAdmobバナー広告を貼る方法
admob事前導入がお済みでない方はこちらを参照してください
boostnote.hatenablog.com
バナー広告の貼り方
最初にテスト表示する時は
ca-app-pub-3940256099942544/2934735716
こちらのテスト用のbannerIDを使用してください。
アカウントが削除される恐れがあります。
今回の実装は
Xcode: v9.1
シミュレータ: iPhone 8 Plus - iOS11.1
を使用しています。
ViewController.swiftに以下のソースコードをコピペすると完了です。
詳細な説明は番号を参照してください。
import GoogleMobileAds // 1 class ViewController: UIViewController, GADBannerViewDelegate { // 2 var bannerView: GADBannerView! override func viewDidLoad() { super.viewDidLoad() // 3 // In this case, we instantiate the banner with desired ad size. bannerView = GADBannerView(adSize: kGADAdSizeBanner) bannerView.adUnitID = "ca-app-pub-3940256099942544/2934735716" bannerView.rootViewController = self bannerView.load(GADRequest()) bannerView.delegate = self addBannerViewToView(bannerView) } // 4 func addBannerViewToView(_ bannerView: GADBannerView) { bannerView.translatesAutoresizingMaskIntoConstraints = false view.addSubview(bannerView) view.addConstraints( [NSLayoutConstraint(item: bannerView, attribute: .bottom, relatedBy: .equal, toItem: bottomLayoutGuide, attribute: .top, multiplier: 1, constant: 0), NSLayoutConstraint(item: bannerView, attribute: .centerX, relatedBy: .equal, toItem: view, attribute: .centerX, multiplier: 1, constant: 0) ]) } // 4 /// Tells the delegate an ad request loaded an ad. func adViewDidReceiveAd(_ bannerView: GADBannerView) { print("adViewDidReceiveAd") } /// Tells the delegate an ad request failed. func adView(_ bannerView: GADBannerView, didFailToReceiveAdWithError error: GADRequestError) { print("adView:didFailToReceiveAdWithError: \(error.localizedDescription)") } /// Tells the delegate that a full-screen view will be presented in response /// to the user clicking on an ad. func adViewWillPresentScreen(_ bannerView: GADBannerView) { print("adViewWillPresentScreen") } /// Tells the delegate that the full-screen view will be dismissed. func adViewWillDismissScreen(_ bannerView: GADBannerView) { print("adViewWillDismissScreen") } /// Tells the delegate that the full-screen view has been dismissed. func adViewDidDismissScreen(_ bannerView: GADBannerView) { print("adViewDidDismissScreen") } /// Tells the delegate that a user click will open another app (such as /// the App Store), backgrounding the current app. func adViewWillLeaveApplication(_ bannerView: GADBannerView) { print("adViewWillLeaveApplication") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
1.事前準備で用意した「GoogleMobileAds」をインポートしてます
2.GADBannerViewDelegateを呼びます
3.BannerViewのサイズなどを指定しています。特に触ることはないです
4.デリゲートメソッドで、広告がロードされた時や、広告の配信に失敗した場合などに、処理を自分で事細かにカスタマイズできます
実際に本物の広告を貼る際には、
bannerView.adUnitID = "ca-app-pub-3940256099942544/2934735716"
このadUnitIDに自分のadmobアカウントで申請したアプリのIDを貼ってください。
以上、SwiftでのAdmobバナー広告の貼り方でした。
Boostnoteのダウンロードはこちらから boostnote.io
GitHub Repository github.com