Skip to content

Instantly share code, notes, and snippets.

@MichaelBarney
Created October 22, 2019 12:28
Show Gist options
  • Save MichaelBarney/0df4e442d54e27d3293db0dd3e08e225 to your computer and use it in GitHub Desktop.
Save MichaelBarney/0df4e442d54e27d3293db0dd3e08e225 to your computer and use it in GitHub Desktop.
A google AdMob Reward implementation in SwiftUI
import SwiftUI
import GoogleMobileAds
import UIKit
final class Rewarded: NSObject, GADRewardedAdDelegate{
var rewardedAd:GADRewardedAd = GADRewardedAd(adUnitID: rewardID)
var rewardFunction: (() -> Void)? = nil
override init() {
super.init()
LoadRewarded()
}
func LoadRewarded(){
let req = GADRequest()
self.rewardedAd.load(req)
}
func showAd(rewardFunction: @escaping () -> Void){
if self.rewardedAd.isReady{
self.rewardFunction = rewardFunction
let root = UIApplication.shared.windows.first?.rootViewController
self.rewardedAd.present(fromRootViewController: root!, delegate: self)
}
else{
print("Not Ready")
}
}
func rewardedAd(_ rewardedAd: GADRewardedAd, userDidEarn reward: GADAdReward) {
if let rf = rewardFunction {
rf()
}
}
func rewardedAdDidDismiss(_ rewardedAd: GADRewardedAd) {
self.rewardedAd = GADRewardedAd(adUnitID: rewardID)
LoadRewarded()
}
}
struct ContentView:View{
var rewardAd:Rewarded
init(){
self.rewardAd = Rewarded()
}
var body : some View{
Button(action: {
self.rewardAd.showAd(rewardFunction: {
print("Give Reward")
}
}){
Text("My Button")
}
}
}
@waha99922
Copy link

showAd() else statement executes and displays "not ready". help.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment