如何在 SwiftUI 中使用 Google 移动广告 SDK,或在 SwiftUI 视图中使用 UIKit UIViewController? [英] How do I use the Google Mobile Ads SDK in SwiftUI, or use the UIKit UIViewController within a SwiftUI view?

查看:39
本文介绍了如何在 SwiftUI 中使用 Google 移动广告 SDK,或在 SwiftUI 视图中使用 UIKit UIViewController?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 SwiftUI 视图,我想在按下按钮时打开来自 Google 移动广告 SDK 的激励广告.加载广告的说明 (https://developers.google.com/admob/ios/rewarded-ads#create_rewarded_ad) 在 UIKit 中,我正在努力在我的 SwiftUI 应用程序中使用它们.有没有办法使用 SwiftUI 加载广告,或者如果我使用 UIKit,我该如何将其集成到 SwiftUI 中?

I have a SwiftUI view that I want to open a rewarded ad from the Google Mobile Ads SDK when I press a button. The instructions for loading the ads (https://developers.google.com/admob/ios/rewarded-ads#create_rewarded_ad) are in UIKit, and I'm struggling to use them in my SwiftUI app. Is there a way to load the ads using SwiftUI, or if I use UIKit, how do I integrate it into SwiftUI?

这是 SwiftUI 父视图:

This is the SwiftUI parent view:

struct AdMenu: View {

    var body: some View {
   NavigationView {
       NavigationLink(destination: Ads())
        {
            Text("Watch Ad")
        }
    }
}
}

我不知道 UIKit,但我认为这是我想在 SwiftUI 中使用的代码:

I don't know UIKit, but I think this is the code I want to use in SwiftUI:

    class ViewController: UIViewController, GADRewardedAdDelegate {

    var rewardedAd: GADRewardedAd?

var adRequestInProgress = false

  @IBAction func doSomething(sender: UIButton) {
    if rewardedAd?.isReady == true {
       rewardedAd?.present(fromRootViewController: self, delegate:self)
    }else {
      let alert = UIAlertController(
        title: "Rewarded video not ready",
        message: "The rewarded video didn't finish loading or failed to load",
        preferredStyle: .alert)
      let alertAction = UIAlertAction(
        title: "OK",
        style: .cancel,
        handler: { [weak self] action in
            // redirect to AdMenu SwiftUI view somehow?
        })
      alert.addAction(alertAction)
      self.present(alert, animated: true, completion: nil)
    }
}

func createAndLoadRewardedAd() {
    rewardedAd = GADRewardedAd(adUnitID: "ca-app-pub-3940256099942544/1712485313")
    adRequestInProgress = true
    rewardedAd?.load(GADRequest()) { error in
      self.adRequestInProgress = false
      if let error = error {
        print("Loading failed: \(error)")
      } else {
        print("Loading Succeeded")
      }
    }
  return rewardedAd
}

// Tells the delegate that the user earned a reward
func rewardedAd(_ rewardedAd: GADRewardedAd, userDidEarn reward: GADAdReward) {
  print("Reward received with currency: \(reward.type), amount \(reward.amount).")
}
// Tells the delegate that the rewarded ad was presented
func rewardedAdDidPresent(_ rewardedAd: GADRewardedAd) {
  print("Rewarded ad presented.")
}
// Tells the delegate that the rewarded ad was dismissed
func rewardedAdDidDismiss(_ rewardedAd: GADRewardedAd) {
  print("Rewarded ad dismissed.")
}
// Tells the delegate that the rewarded ad failed to present
func rewardedAd(_ rewardedAd: GADRewardedAd, didFailToPresentWithError error: Error) {
    rewardedAd = createAndLoadRewardedAd()
    print("Rewarded ad failed to present.")
}

    override func viewDidLoad() {
        super.viewDidLoad()
    if !adRequestInProgress && !(rewardedAd?.isReady ?? false) {
    rewardedAd = createAndLoadRewardedAd()
}

推荐答案

我使用了一个非常简单的方法.我有一个委托类,它加载奖励广告并通知视图它已加载,因此视图呈现它.当用户观看完整的广告时,同一个委托会收到成功回调并通知视图.

I have used a very simple approach. I have a delegate class which loads the rewarded Ad and informs the view that its loaded, hence the view presents it. When user watches the full Ad, same delegate gets the success callback and it informs the view about it.

委托代码如下所示:-

class RewardedAdDelegate: NSObject, GADRewardedAdDelegate, ObservableObject {
@Published var adLoaded: Bool = false
@Published var adFullyWatched: Bool = false

var rewardedAd: GADRewardedAd? = nil

func loadAd() {
    rewardedAd = GADRewardedAd(adUnitID: "ca-app-pub-3940256099942544/1712485313")
        rewardedAd!.load(GADRequest()) { error in
          if error != nil {
            self.adLoaded = false
          } else {
            self.adLoaded = true
          }
        }
}

/// Tells the delegate that the user earned a reward.
func rewardedAd(_ rewardedAd: GADRewardedAd, userDidEarn reward: GADAdReward) {
    adFullyWatched = true
}

/// Tells the delegate that the rewarded ad was presented.
func rewardedAdDidPresent(_ rewardedAd: GADRewardedAd) {
     self.adLoaded = false
}

/// Tells the delegate that the rewarded ad was dismissed.
func rewardedAdDidDismiss(_ rewardedAd: GADRewardedAd) {}

/// Tells the delegate that the rewarded ad failed to present.
func rewardedAd(_ rewardedAd: GADRewardedAd, didFailToPresentWithError error: Error) {}
}

现在您需要一个视图来启动和展示奖励广告:-

struct RewardedAd: View {
@ObservedObject var adDelegate = RewardedAdDelegate()

var body: some View {
    if adDelegate.adLoaded && !adDelegate.adFullyWatched {
        let root = UIApplication.shared.windows.first?.rootViewController
        self.adDelegate.rewardedAd!.present(fromRootViewController: root!, delegate: adDelegate)
    }
    
    return Text("Load ad").onTapGesture {
        self.adDelegate.loadAd()
    }
}
}

解释:-在上面的视图中,当用户点击 Load Ad 时,我们启动加载,然后委托更新已发布的布尔值.这通知我们的观点,广告已加载,我们调用:-

Explanation:- In the above view when user taps on Load Ad, we initiate the loading and then the delegate updates the Published Boolean. This informs our view that ad is Loaded and we call:-

let root = UIApplication.shared.windows.first?.rootViewControllerself.adDelegate.rewardedAd!.present(fromRootViewController: root!, delegate: adDelegate)

let root = UIApplication.shared.windows.first?.rootViewController self.adDelegate.rewardedAd!.present(fromRootViewController: root!, delegate: adDelegate)

广告现在正在屏幕上播放,如果用户完全观看,委托将收到成功回调,并更新另一个已发布的布尔值.这将通知我们我们现在需要奖励用户(您可以添加处理/奖励用户的方式).

The Ad is now playing on screen and if user watches is completely, the delegate will get a success callback and it'll update another Published Boolean. This will inform us that we need to reward the user now (you can add your way to handle/reward the user).

我希望这会有所帮助.快乐编码...

I hope this helps. Happy coding...

这篇关于如何在 SwiftUI 中使用 Google 移动广告 SDK,或在 SwiftUI 视图中使用 UIKit UIViewController?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆