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?
This is the SwiftUI parent view:
struct AdMenu: View {
var body: some View {
NavigationView {
NavigationLink(destination: Ads())
{
Text("Watch Ad")
}
}
}
}
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()
}