Created
October 22, 2019 12:28
-
-
Save MichaelBarney/0df4e442d54e27d3293db0dd3e08e225 to your computer and use it in GitHub Desktop.
A google AdMob Reward implementation in SwiftUI
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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") | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
showAd() else statement executes and displays "not ready". help.