Skip to content

Instantly share code, notes, and snippets.

@git-init-wesley
Created February 24, 2021 19:40
Show Gist options
  • Save git-init-wesley/a4636f62a530850b5947e9acdf9123de to your computer and use it in GitHub Desktop.
Save git-init-wesley/a4636f62a530850b5947e9acdf9123de to your computer and use it in GitHub Desktop.
Using GoogleMobileAds (SDK: v7.X.X), for Reward Ads.
//MARK: - Rewarded
final class Rewarded: NSObject, ObservableObject, GADRewardedAdDelegate {
@Published var isReady: Bool = false
private var adUnitID: String = ""
private var ad:GADRewardedAd?
private var adFunction: ((Bool) -> ())?
override init() {
super.init()
}
func start(adUnitID: String) -> Rewarded {
self.adUnitID = adUnitID
self.load()
self.observe()
return self
}
private func load() {
self.ad = GADRewardedAd(adUnitID: self.adUnitID)
self.ad!.load(GADRequest())
}
private func observe() {
DispatchQueue.main.asyncAfter(deadline: .now() + 30) {
self.isReady = self.ad != nil ? self.ad!.isReady : false
self.observe()
}
}
func showAd(rewardFunction: @escaping (Bool) -> ()){
self.adFunction = rewardFunction
if self.ad!.isReady {
let root = UIApplication.shared.windows.first?.rootViewController
self.ad!.present(fromRootViewController: root!, delegate: self)
} else {
if self.adFunction != nil {
self.adFunction.unsafelyUnwrapped(false)
}
self.load()
}
}
func rewardedAd(_ rewardedAd: GADRewardedAd, userDidEarn reward: GADAdReward) {
if self.adFunction != nil {
self.adFunction.unsafelyUnwrapped(true)
}
self.load()
}
func rewardedAdDidDismiss(_ rewardedAd: GADRewardedAd) {
if self.adFunction != nil {
self.adFunction.unsafelyUnwrapped(false)
}
self.load()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment