LoginSignup
7
5

More than 1 year has passed since last update.

【SwiftUI】ネイティブ広告の表示方法

Last updated at Posted at 2022-05-12

第0部: スタートガイド

第1部: リワード広告
第2部: インタースティシャル広告
第3部: ネイティブ広告 ← イマココ
第4部: バナー広告
第5部: アプリ起動広告

はじめに

AdMob広告シリーズ第3部です
今回はネイティブ広告です。
見た目的にはバナー広告に近いように思います。
バナー広告と違う点は広告のUIが変更可能という事です。
これによりアプリに馴染ませることができ、UXの向上につながります。
image.png

今回は公式から提供されているデモレイアウトを使用してネイティブ広告を実装していこうと思います。

実装準備

実装の前にスタートガイドに記載してある事を行います

①: Mobile Ads SDK のインポート
②: Info.plist の更新
③: Mobile Ads SDK の初期化

こちらで詳しく解説してあります。
これが終われば準備は完了です。

実装

こちらからAdMob広告サンプルプロジェクトをダウンロードします。
スクリーンショット 2022-05-12 20.55.14.png
ダウンロードしたファイルからNativeAdView.xidを探します。
スクリーンショット 2022-05-12 20.57.39.png
NativeAdView.xidをプロジェクト内にドラッグします。
スクリーンショット 2022-05-12 20.59.48.png
Copy item if neededにチェックを入れてFinishを押します。
スクリーンショット 2022-05-12 21.00.05.png

NativeAdView.xibをオリジナルUIに変更しましょう
スクリーンショット 2022-05-12 21.22.00.png

私はこんな感じにアレンジしました。
どんな風になったかは最後にスクショ載せときます。
スクリーンショット 2022-05-12 22.06.18.png

Native.swift
import SwiftUI
import GoogleMobileAds

struct NativeView: UIViewControllerRepresentable {
    func makeUIViewController(context: Context) -> UIViewController {
        let viewController = GADNativeViewController()
        return viewController
    }
    func updateUIViewController(_ uiViewController: UIViewController, context: Context) {
    }
}

class GADNativeViewController: UIViewController, GADNativeAdDelegate, GADNativeAdLoaderDelegate {
    var heightConstraint: NSLayoutConstraint?
    var adLoader: GADAdLoader!
    var nativeAdView: GADNativeAdView!
    let adUnitID = "ca-app-pub-3940256099942544/3986624511"

    override func viewDidLoad() {
        super.viewDidLoad()

        guard
            let nibObjects = Bundle.main.loadNibNamed("NativeAdView", owner: nil, options: nil),
            let adView = nibObjects.first as? GADNativeAdView
        else {
            return assert(false, "Could not load nib file for adView")
        }
        setAdView(adView)
        refreshAd()
    }

    func setAdView(_ view: GADNativeAdView) {

        nativeAdView = view
        self.view.addSubview(nativeAdView)
        nativeAdView.translatesAutoresizingMaskIntoConstraints = false
        let viewDictionary = ["_nativeAdView": nativeAdView!]
        self.view.addConstraints(
            NSLayoutConstraint.constraints(
                withVisualFormat: "H:|[_nativeAdView]|",
                options: NSLayoutConstraint.FormatOptions(rawValue: 0), metrics: nil, views: viewDictionary)
        )
        self.view.addConstraints(
            NSLayoutConstraint.constraints(
                withVisualFormat: "V:|[_nativeAdView]|",
                options: NSLayoutConstraint.FormatOptions(rawValue: 0), metrics: nil, views: viewDictionary)
        )
    }
    func refreshAd() {
        adLoader = GADAdLoader(
            adUnitID: adUnitID, rootViewController: self,
            adTypes: [.native], options: nil)
        adLoader.delegate = self
        adLoader.load(GADRequest())
    }
    func imageOfStars(from starRating: NSDecimalNumber?) -> UIImage? {
        guard let rating = starRating?.doubleValue else {
            return nil
        }
        if rating >= 5 {
            return UIImage(named: "stars_5")
        } else if rating >= 4.5 {
            return UIImage(named: "stars_4_5")
        } else if rating >= 4 {
            return UIImage(named: "stars_4")
        } else if rating >= 3.5 {
            return UIImage(named: "stars_3_5")
        } else {
            return nil
        }
    }
    func adLoader(_ adLoader: GADAdLoader, didReceive nativeAd: GADNativeAd) {
        nativeAd.delegate = self
        heightConstraint?.isActive = false
        (nativeAdView.headlineView as? UILabel)?.text = nativeAd.headline
        (nativeAdView.bodyView as? UILabel)?.text = nativeAd.body
        nativeAdView.bodyView?.isHidden = nativeAd.body == nil

        (nativeAdView.callToActionView as? UIButton)?.setTitle(nativeAd.callToAction, for: .normal)
        nativeAdView.callToActionView?.isHidden = nativeAd.callToAction == nil

        (nativeAdView.iconView as? UIImageView)?.image = nativeAd.icon?.image
        nativeAdView.iconView?.isHidden = nativeAd.icon == nil

        (nativeAdView.starRatingView as? UIImageView)?.image = imageOfStars(from: nativeAd.starRating)
        nativeAdView.starRatingView?.isHidden = nativeAd.starRating == nil

        (nativeAdView.storeView as? UILabel)?.text = nativeAd.store
        nativeAdView.storeView?.isHidden = nativeAd.store == nil

        (nativeAdView.priceView as? UILabel)?.text = nativeAd.price
        nativeAdView.priceView?.isHidden = nativeAd.price == nil

        (nativeAdView.advertiserView as? UILabel)?.text = nativeAd.advertiser
        nativeAdView.advertiserView?.isHidden = nativeAd.advertiser == nil

        nativeAdView.callToActionView?.isUserInteractionEnabled = false

        nativeAdView.nativeAd = nativeAd
    }
    func adLoader(_ adLoader: GADAdLoader, didFailToReceiveAdWithError error: Error) {
        print("\(adLoader) failed with error: \(error.localizedDescription)")
    }
}
ContentView.swift
import SwiftUI

struct ContentView: View {
    var body: some View {
        NativeView()
            .frame(height: 160)
    }
}

完成!!!
IMG_0257.PNG
いい感じになりました

おわり

今回作成したプロジェクトを置いとくので参考にしてください。

7
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
5