admobのバナー、インターステイシャル、リワード広告
リワード広告を視聴すると60分間他の広告も消えます。
今度別記事にて私が考えたネイティブ広告型のポップアップ記事も今度投稿します。
目次
ViewController
class ViewController: UIViewController,GADInterstitialDelegate,GADRewardBasedVideoAdDelegate{ //広告 @IBOutlet var bannerView: GADBannerView! var interstitial: GADInterstitial? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. //表示 loadAdMobIntersBanner() } func viewWillAds(){ // Check Banner Ads available and show/hide BannerAds let admobBoolResult = defaults.bool(forKey:SharedInfos.shared.productIdentifiers[0]) defaults.synchronize() var packageAuto = 0 let autoBool = defaults.bool(forKey:SharedInfos.shared.productIdentifiers[1]) defaults.synchronize() if autoBool { packageAuto = 1 } if (admobBoolResult||packageAuto >= 1) { self.hideBannerView() //self.watchAdsBtn.isHidden = true } else { let isLoadRewardAds: Bool = SharedInfos.shared.getIntervalTimeAds() if isLoadRewardAds == false { self.hideBannerView() //self.watchAdsBtn.isHidden = true } else { self.showBannerView() //self.watchAdsBtn.isHidden = false self.bannerView.adUnitID = bannerID bannerView.rootViewController = self let request = GADRequest() request.testDevices = [ kGADSimulatorID ] as! [String]; // All simulators bannerView.load(request) // self.bannerView.adUnitID = bannerID // bannerView.rootViewController = self // let request = GADRequest() // request.testDevices = [ kGADSimulatorID ] as! [String]; // All simulators // bannerView.load(request) } } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) //少し遅延させた方が課金やリワード広告視聴後の判定にいい鴨 let delayTime = DispatchTime.now() + .seconds(1) DispatchQueue.main.asyncAfter(deadline: delayTime) { self.viewWillAds(); } } /////////////////////////////////////////////////// // Mark - Interstital Ads load function /////////////////////////////////////////////////// func loadAdMobIntersBanner() { // Check InterstitialAds available and Show let admobBoolResult = defaults.bool(forKey:SharedInfos.shared.productIdentifiers[0]) defaults.synchronize() var packageAuto = 0 let autoBool = defaults.bool(forKey:SharedInfos.shared.productIdentifiers[1]) defaults.synchronize() if autoBool { packageAuto = 1 } if (admobBoolResult||packageAuto >= 1) { return } else { let isLoadRewardAds: Bool = SharedInfos.shared.getIntervalTimeAds() if isLoadRewardAds == false { return } else { interstitial = GADInterstitial(adUnitID: interstitialID) interstitial!.delegate = self let request = GADRequest() request.testDevices = [ kGADSimulatorID ] as! [String]; // All simulators interstitial?.load(request) } } } // Interstitial Ads delegate functions func interstitialDidFailToReceiveAdWithError ( interstitial: GADInterstitial, error: GADRequestError) { print("TableView : interstitialDidFailToReceiveAdWithError: %@" + error.localizedDescription) } func interstitialDidDismissScreen (_ interstitial: GADInterstitial) { print("TableView : interstitialDidDismissScreen") } func interstitialDidReceiveAd(_ ad: GADInterstitial) { print("TableView : interstitialDidReceiveAd") interstitial!.present(fromRootViewController: self) } /////////////////////////////////////////////////// // Mark - RewaredAds Functions /////////////////////////////////////////////////// @IBAction func onclickWatchAdsBtn(_ sender: Any) { // click "WatchAds" button to show rewarded Ads GADRewardBasedVideoAd.sharedInstance().delegate = self let request = GADRequest() request.testDevices = [kGADSimulatorID] as! [String] GADRewardBasedVideoAd.sharedInstance().load(request, withAdUnitID:rewardedID) print("onclickWatchAdsBtn"); } func loadAdMobReward(){ let isLoadRewardAds: Bool = SharedInfos.shared.getIntervalTimeAds() if isLoadRewardAds == true { if GADRewardBasedVideoAd.sharedInstance().isReady { GADRewardBasedVideoAd.sharedInstance().present(fromRootViewController: self) } else { let localStr = NSLocalizedString("adsAlert1", comment: "") utilityAlert(string: localStr) } } } func rewardBasedVideoAd(_ rewardBasedVideoAd: GADRewardBasedVideoAd, didFailToLoadWithError error: Error) { print("SettingView : didFailToLoadWithError :", error.localizedDescription) let localStr = NSLocalizedString("adsAlert2", comment: "") utilityAlert(string: localStr) } func rewardBasedVideoAdDidReceive(_ rewardBasedVideoAd: GADRewardBasedVideoAd) { print("SettingView : rewardBasedVideoAdDidReceive") loadAdMobReward() } func rewardBasedVideoAdDidOpen(_ rewardBasedVideoAd: GADRewardBasedVideoAd) { print("SettingView : rewardBasedVideoAdDidOpen") } func rewardBasedVideoAdDidStartPlaying(_ rewardBasedVideoAd: GADRewardBasedVideoAd) { print("SettingView : rewardBasedVideoAdDidStartPlaying") } func rewardBasedVideoAdDidClose(_ rewardBasedVideoAd: GADRewardBasedVideoAd) { print("SettingView : rewardBasedVideoAdDidClose") } func rewardBasedVideoAdWillLeaveApplication(_ rewardBasedVideoAd: GADRewardBasedVideoAd) { print("SettingView : rewardBasedVideoAdWillLeaveApplication") } func rewardBasedVideoAd(_ rewardBasedVideoAd: GADRewardBasedVideoAd, didRewardUserWith reward: GADAdReward) { print("SettingView : Reward received with currency: \(reward.type), amount \(reward.amount).") //リワード視聴完了時に呼ばれる earnCoins(NSInteger(truncating: reward.amount)) } // Set rewarded time fileprivate func earnCoins(_ coins: NSInteger) { userDefaults.set(Date(), forKey: "rewardInterval") userDefaults.synchronize() print("SettingView : Set new rewarded time") //とにかく消す self.hideBannerView() } // Alert functions for rewardedAds func utilityAlert(string:String) { let alert = UIAlertController(title: "", message: "\(string)", preferredStyle: UIAlertController.Style.alert) self.present(alert, animated: true, completion: nil) let localStr = NSLocalizedString("alertOKBtn", comment: "") alert.addAction(UIAlertAction(title: localStr, style: .default, handler: { action in switch action.style{ case .default: print("SettingView : utilityAlert default") case .cancel: print("SettingView : utilityAlert cancel") case .destructive: print("SettingView : utilityAlert destructive") } })) } // Hide/Show BannerAds Functions func hideBannerView() { if self.bannerView.isHidden == true { return } self.bannerView.isHidden = true } func showBannerView() { if self.bannerView.isHidden == false { return } self.bannerView.isHidden = false } }
SharedInfos.swift
public let adsAppID = "ca-app-pub-3940256099942544~1458002511" public let bannerID = "ca-app-pub-3940256099942544/2934735716" public let interstitialID = "ca-app-pub-3940256099942544/4411468910" public let rewardedID = "ca-app-pub-3940256099942544/1712485313" public let nativeID = "ca-app-pub-3940256099942544/1712485313" //obj-cからアクセスするのに必要 @objcMembers class SharedInfos: NSObject { static let shared: SharedInfos = SharedInfos() var productIdentifiers : [String] = ["りんごアホ非消耗型","りんごアホサブスクリプション"] var localStoreUpdate: Bool // localstore update flag override init() { localStoreUpdate = false } // check AdsRewarded time and return hide/show Ads func getIntervalTimeAds() -> Bool { let defaults = UserDefaults.standard let rewardIntervalDate = defaults.object(forKey: "rewardInterval") as! Date! if rewardIntervalDate == nil { return true } let retInterval:Double! = rewardIntervalDate?.timeIntervalSinceNow let ret = retInterval/60 if ret > -60 { return false } else { return true } } func printModelName()-> String{ NSLog("Model Name: %@", UIDevice.modelName()) return UIDevice.modelName() } }
おまけ(Localizable.strings)
ローカライズに対応
"alertOKBtn" = "確認"; "storeUpdate" = "データベース更新中"; "storeError" = "更新失敗!"; "storeFinish" = "アップデート成功!"; "InnAppMsg1" = "商品情報の取得に失敗"; "InnAppMsg2" = "商品がありません!"; "InnAppMsg3" = "課金完了(中断していたもの)"; "InnAppMsg4" = "課金失敗"; "InnAppMsg5" = "リストア完了"; "InnAppMsg6" = "課金 承認待ち"; "InnAppMsg7" = "メールは送信できません";