From 364cf0e6d06cb01579daaaca9a73d4cbcbfbbaee Mon Sep 17 00:00:00 2001 From: Mobile Ads Developer Relations Date: Fri, 22 Nov 2019 16:48:01 -0800 Subject: [PATCH] Swift UIAlertView cleanup PiperOrigin-RevId: 282068505 --- .../MySimpleNativeAdView.swift | 49 +++++--- .../ViewController.swift | 86 ++++++++------ .../Podfile.lock | 4 +- .../project.pbxproj | 1 - .../ViewController.swift | 72 +++++++----- .../AdManagerInterstitialExample/Podfile.lock | 4 +- .../ViewController.swift | 71 +++++++----- .../Podfile.lock | 4 +- .../admob/AdaptiveBannerExample/Podfile.lock | 4 +- Swift/admob/BannerExample/Podfile.lock | 4 +- .../InterstitialExample/ViewController.swift | 74 +++++++----- ...ManagerMultipleAdSizesViewController.swift | 34 ++++-- .../APIDemo/AdManagerPPIDViewController.swift | 23 ++-- .../APIDemo/APIDemo/SimpleNativeAdView.swift | 109 ++++++++++-------- Swift/advanced/APIDemo/Podfile.lock | 4 +- 15 files changed, 316 insertions(+), 227 deletions(-) diff --git a/Swift/admanager/AdManagerCustomRenderingExample/AdManagerCustomRenderingExample/MySimpleNativeAdView.swift b/Swift/admanager/AdManagerCustomRenderingExample/AdManagerCustomRenderingExample/MySimpleNativeAdView.swift index 3c11d2d9..2466b86e 100644 --- a/Swift/admanager/AdManagerCustomRenderingExample/AdManagerCustomRenderingExample/MySimpleNativeAdView.swift +++ b/Swift/admanager/AdManagerCustomRenderingExample/AdManagerCustomRenderingExample/MySimpleNativeAdView.swift @@ -18,7 +18,7 @@ import GoogleMobileAds import UIKit /// Custom native ad view struct that defines the custom ad template asset keys as type properties. -struct MySimpleNativeAdViewTypeProperties { +enum MySimpleNativeAdViewTypeProperties { /// The headline asset key. static let MySimpleNativeAdViewHeadlineKey = "Headline" @@ -35,6 +35,7 @@ class MySimpleNativeAdView: UIView { /// Weak references to this ad's asset views. @IBOutlet weak var headlineView: UILabel! + @IBOutlet weak var mainPlaceholder: UIView! @IBOutlet weak var captionView: UILabel! @@ -45,14 +46,16 @@ class MySimpleNativeAdView: UIView { super.awakeFromNib() // Enable clicks on the main image. - mainPlaceholder.addGestureRecognizer(UITapGestureRecognizer(target: self, + mainPlaceholder.addGestureRecognizer( + UITapGestureRecognizer( + target: self, action: #selector(MySimpleNativeAdView.performClickOnMainImage(_:)))) mainPlaceholder.isUserInteractionEnabled = true } @objc func performClickOnMainImage(_ sender: UIImage!) { customNativeAd.performClickOnAsset( - withKey: MySimpleNativeAdViewTypeProperties.MySimpleNativeAdViewMainImageKey) + withKey: MySimpleNativeAdViewTypeProperties.MySimpleNativeAdViewMainImageKey) } /// Populates the ad view with the custom native ad object. @@ -60,10 +63,17 @@ class MySimpleNativeAdView: UIView { self.customNativeAd = customNativeAd // The custom click handler closure overrides the normal click action defined by the ad. customNativeAd.customClickHandler = { assetID in - let alertView = UIAlertView(title: "Custom Click", message: "You just clicked on the image!", - delegate: self, cancelButtonTitle: "OK") - alertView.alertViewStyle = .default - alertView.show() + let alert = UIAlertController( + title: "Custom Click", + message: "You just clicked on the image!", + preferredStyle: .alert) + let alertAction = UIAlertAction( + title: "OK", + style: .cancel, + handler: nil) + alert.addAction(alertAction) + UIApplication.shared.keyWindow?.rootViewController?.present( + alert, animated: true, completion: nil) } // Populate the custom native ad assets. @@ -78,9 +88,10 @@ class MySimpleNativeAdView: UIView { /// This custom native ad also has a both a video and image associated with it. We'll use the /// video asset if available, and otherwise fallback to the image asset. - private func mainView(forCustomNativeAd customNativeAd:GADNativeCustomTemplateAd) -> UIView { + private func mainView(forCustomNativeAd customNativeAd: GADNativeCustomTemplateAd) -> UIView { if customNativeAd.videoController.hasVideoContent(), - let mediaView = customNativeAd.mediaView { + let mediaView = customNativeAd.mediaView + { return mediaView } else { let imageKey = MySimpleNativeAdViewTypeProperties.MySimpleNativeAdViewMainImageKey @@ -89,21 +100,23 @@ class MySimpleNativeAdView: UIView { } } - private func updateMainView(_ mainView:UIView) { + private func updateMainView(_ mainView: UIView) { // Remove all the media placeholder's subviews. - for subview: UIView in mainPlaceholder.subviews { + for subview:UIView in mainPlaceholder.subviews { subview.removeFromSuperview() } mainPlaceholder.addSubview(mainView) // Size the media view to fill our container size. mainView.translatesAutoresizingMaskIntoConstraints = false - let viewDictionary: [AnyHashable: Any] = ["mainView":mainView] - mainPlaceholder.addConstraints(NSLayoutConstraint.constraints( - withVisualFormat: "H:|[mainView]|", options: [], metrics: nil, - views: viewDictionary as? [String : Any] ?? [String : Any]())) - mainPlaceholder.addConstraints(NSLayoutConstraint.constraints( - withVisualFormat: "V:|[mainView]|", options: [], metrics: nil, - views: viewDictionary as? [String : Any] ?? [String : Any]())) + let viewDictionary: [AnyHashable: Any] = ["mainView": mainView] + mainPlaceholder.addConstraints( + NSLayoutConstraint.constraints( + withVisualFormat: "H:|[mainView]|", options: [], metrics: nil, + views: viewDictionary as? [String: Any] ?? [String: Any]())) + mainPlaceholder.addConstraints( + NSLayoutConstraint.constraints( + withVisualFormat: "V:|[mainView]|", options: [], metrics: nil, + views: viewDictionary as? [String: Any] ?? [String: Any]())) } } diff --git a/Swift/admanager/AdManagerCustomRenderingExample/AdManagerCustomRenderingExample/ViewController.swift b/Swift/admanager/AdManagerCustomRenderingExample/AdManagerCustomRenderingExample/ViewController.swift index 30f7066d..ccdf0c05 100644 --- a/Swift/admanager/AdManagerCustomRenderingExample/AdManagerCustomRenderingExample/ViewController.swift +++ b/Swift/admanager/AdManagerCustomRenderingExample/AdManagerCustomRenderingExample/ViewController.swift @@ -69,10 +69,16 @@ class ViewController: UIViewController { // Layout constraints for positioning the native ad view to stretch the entire width and height // of the nativeAdPlaceholder. let viewDictionary = ["_nativeAdView": nativeAdView!] - self.view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[_nativeAdView]|", - options: NSLayoutConstraint.FormatOptions(rawValue: 0), metrics: nil, views: viewDictionary)) - self.view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[_nativeAdView]|", - options: NSLayoutConstraint.FormatOptions(rawValue: 0), metrics: nil, views: viewDictionary)) + self.view.addConstraints( + NSLayoutConstraint.constraints( + withVisualFormat: "H:|[_nativeAdView]|", + options: NSLayoutConstraint.FormatOptions(rawValue: 0), metrics: nil, views: viewDictionary) + ) + self.view.addConstraints( + NSLayoutConstraint.constraints( + withVisualFormat: "V:|[_nativeAdView]|", + options: NSLayoutConstraint.FormatOptions(rawValue: 0), metrics: nil, views: viewDictionary) + ) } // MARK: - Actions @@ -88,16 +94,23 @@ class ViewController: UIViewController { } if adTypes.isEmpty { - let alertView = UIAlertView(title: "Alert", message: "At least one ad format must be " + - "selected to refresh the ad.", delegate: self, cancelButtonTitle: "OK") - alertView.alertViewStyle = .default - alertView.show() + let alert = UIAlertController( + title: "Alert", + message: "At least one ad format must be selected to refresh the ad.", + preferredStyle: .alert) + let alertAction = UIAlertAction( + title: "OK", + style: .cancel, + handler: nil) + alert.addAction(alertAction) + self.present(alert, animated: true, completion: nil) } else { refreshAdButton.isEnabled = false let videoOptions = GADVideoOptions() videoOptions.startMuted = startMutedSwitch.isOn - adLoader = GADAdLoader(adUnitID: adUnitID, rootViewController: self, - adTypes: adTypes, options: [videoOptions]) + adLoader = GADAdLoader( + adUnitID: adUnitID, rootViewController: self, + adTypes: adTypes, options: [videoOptions]) adLoader.delegate = self adLoader.load(GADRequest()) videoStatusLabel.text = "" @@ -133,8 +146,7 @@ class ViewController: UIViewController { // By acting as the delegate to the GADVideoController, this ViewController receives messages // about events in the video lifecycle. videoStatusLabel.text = "Ad contains a video asset." - } - else { + } else { videoStatusLabel.text = "Ad does not contain a video." } } @@ -142,7 +154,7 @@ class ViewController: UIViewController { } // MARK: - GADAdLoaderDelegate -extension ViewController : GADAdLoaderDelegate { +extension ViewController: GADAdLoaderDelegate { func adLoader(_ adLoader: GADAdLoader, didFailToReceiveAdWithError error: GADRequestError) { print("\(adLoader) failed with error: \(error.localizedDescription)") refreshAdButton.isEnabled = true @@ -150,7 +162,7 @@ extension ViewController : GADAdLoaderDelegate { } // MARK: - GADUnifiedNativeAdLoaderDelegate -extension ViewController : GADUnifiedNativeAdLoaderDelegate { +extension ViewController: GADUnifiedNativeAdLoaderDelegate { func adLoader(_ adLoader: GADAdLoader, didReceive nativeAd: GADUnifiedNativeAd) { print("Received unified native ad: \(nativeAd)") @@ -174,9 +186,9 @@ extension ViewController : GADUnifiedNativeAdLoaderDelegate { // Some native ads will include a video asset, while others do not. Apps can use the // GADVideoController's hasVideoContent property to determine if one is present, and adjust their // UI accordingly. - let hasVideoContent = nativeAd.mediaContent.hasVideoContent // Update the ViewController for video content. + let hasVideoContent = nativeAd.mediaContent.hasVideoContent // Update the ViewController for video content. updateVideoStatusLabel(hasVideoContent: hasVideoContent) - if (hasVideoContent) { + if hasVideoContent { // By acting as the delegate to the GADVideoController, this ViewController receives messages // about events in the video lifecycle. nativeAd.mediaContent.videoController.delegate = self @@ -185,13 +197,14 @@ extension ViewController : GADUnifiedNativeAdLoaderDelegate { // This app uses a fixed width for the GADMediaView and changes its height to match the aspect // ratio of the media it displays. if let mediaView = nativeAdView.mediaView, nativeAd.mediaContent.aspectRatio > 0 { - let heightConstraint = NSLayoutConstraint(item: mediaView, - attribute: .height, - relatedBy: .equal, - toItem: mediaView, - attribute: .width, - multiplier: CGFloat(1 / nativeAd.mediaContent.aspectRatio), - constant: 0) + let heightConstraint = NSLayoutConstraint( + item: mediaView, + attribute: .height, + relatedBy: .equal, + toItem: mediaView, + attribute: .width, + multiplier: CGFloat(1 / nativeAd.mediaContent.aspectRatio), + constant: 0) heightConstraint.isActive = true } @@ -206,7 +219,8 @@ extension ViewController : GADUnifiedNativeAdLoaderDelegate { (nativeAdView.iconView as? UIImageView)?.image = nativeAd.icon?.image nativeAdView.iconView?.isHidden = nativeAd.icon == nil - (nativeAdView.starRatingView as? UIImageView)?.image = imageOfStars(fromStarRating:nativeAd.starRating) + (nativeAdView.starRatingView as? UIImageView)?.image = imageOfStars( + fromStarRating: nativeAd.starRating) nativeAdView.starRatingView?.isHidden = nativeAd.starRating == nil (nativeAdView.storeView as? UILabel)?.text = nativeAd.store @@ -223,30 +237,32 @@ extension ViewController : GADUnifiedNativeAdLoaderDelegate { } } - // MARK: - GADNativeCustomTemplateAdLoaderDelegate -extension ViewController : GADNativeCustomTemplateAdLoaderDelegate { +extension ViewController: GADNativeCustomTemplateAdLoaderDelegate { func nativeCustomTemplateIDs(for adLoader: GADAdLoader) -> [String] { - return [ nativeCustomTemplateId ] + return [nativeCustomTemplateId] } - func adLoader(_ adLoader: GADAdLoader, - didReceive nativeCustomTemplateAd: GADNativeCustomTemplateAd) { + func adLoader( + _ adLoader: GADAdLoader, + didReceive nativeCustomTemplateAd: GADNativeCustomTemplateAd + ) { print("Received custom native ad: \(nativeCustomTemplateAd)") refreshAdButton.isEnabled = true // Create and place the ad in the view hierarchy. - let customNativeAdView = Bundle.main.loadNibNamed( - "SimpleCustomNativeAdView", owner: nil, options: nil)!.first as! MySimpleNativeAdView + let customNativeAdView = + Bundle.main.loadNibNamed( + "SimpleCustomNativeAdView", owner: nil, options: nil)!.first as! MySimpleNativeAdView setAdView(customNativeAdView) let hasVideoContent = nativeCustomTemplateAd.videoController.hasVideoContent() // Update the ViewController for video content. updateVideoStatusLabel(hasVideoContent: hasVideoContent) - if (hasVideoContent) { + if hasVideoContent { nativeCustomTemplateAd.videoController.delegate = self } // Populate the custom native ad view with the custom native ad assets. - customNativeAdView.populate(withCustomNativeAd:nativeCustomTemplateAd) + customNativeAdView.populate(withCustomNativeAd: nativeCustomTemplateAd) // Impressions for custom template format must be manually tracked. If this is not called, // videos will also not be played. nativeCustomTemplateAd.recordImpression() @@ -254,7 +270,7 @@ extension ViewController : GADNativeCustomTemplateAdLoaderDelegate { } // MARK: - GADVideoControllerDelegate implementation -extension ViewController : GADVideoControllerDelegate { +extension ViewController: GADVideoControllerDelegate { func videoControllerDidEndVideoPlayback(_ videoController: GADVideoController) { videoStatusLabel.text = "Video playback has ended." @@ -262,7 +278,7 @@ extension ViewController : GADVideoControllerDelegate { } // MARK: - GADUnifiedNativeAdDelegate implementation -extension ViewController : GADUnifiedNativeAdDelegate { +extension ViewController: GADUnifiedNativeAdDelegate { func nativeAdDidRecordClick(_ nativeAd: GADUnifiedNativeAd) { print("\(#function) called") diff --git a/Swift/admanager/AdManagerCustomRenderingExample/Podfile.lock b/Swift/admanager/AdManagerCustomRenderingExample/Podfile.lock index 53143fd1..fec693c4 100644 --- a/Swift/admanager/AdManagerCustomRenderingExample/Podfile.lock +++ b/Swift/admanager/AdManagerCustomRenderingExample/Podfile.lock @@ -33,7 +33,7 @@ DEPENDENCIES: - Google-Mobile-Ads-SDK SPEC REPOS: - https://github.com/CocoaPods/Specs.git: + https://github.com/CocoaPods/Specs: - Google-Mobile-Ads-SDK - GoogleAppMeasurement - GoogleUtilities @@ -47,4 +47,4 @@ SPEC CHECKSUMS: PODFILE CHECKSUM: f7c41e035c07771ca0e5c5c7964b9164b2b0bc7d -COCOAPODS: 1.8.0 +COCOAPODS: 1.8.4 diff --git a/Swift/admanager/AdManagerInterstitialExample/AdManagerInterstitialExample.xcodeproj/project.pbxproj b/Swift/admanager/AdManagerInterstitialExample/AdManagerInterstitialExample.xcodeproj/project.pbxproj index a6d6a3bb..9fbc6b48 100644 --- a/Swift/admanager/AdManagerInterstitialExample/AdManagerInterstitialExample.xcodeproj/project.pbxproj +++ b/Swift/admanager/AdManagerInterstitialExample/AdManagerInterstitialExample.xcodeproj/project.pbxproj @@ -97,7 +97,6 @@ TargetAttributes = { 84FEE90E1B0D65A8006C8148 = { CreatedOnToolsVersion = 6.2; - LastSwiftMigration = 0900; }; }; diff --git a/Swift/admanager/AdManagerInterstitialExample/AdManagerInterstitialExample/ViewController.swift b/Swift/admanager/AdManagerInterstitialExample/AdManagerInterstitialExample/ViewController.swift index 2248336e..a301342d 100644 --- a/Swift/admanager/AdManagerInterstitialExample/AdManagerInterstitialExample/ViewController.swift +++ b/Swift/admanager/AdManagerInterstitialExample/AdManagerInterstitialExample/ViewController.swift @@ -17,7 +17,7 @@ import GoogleMobileAds import UIKit -class ViewController: UIViewController, GADInterstitialDelegate, UIAlertViewDelegate { +class ViewController: UIViewController, GADInterstitialDelegate { enum GameState: NSInteger { case notStarted @@ -57,14 +57,16 @@ class ViewController: UIViewController, GADInterstitialDelegate, UIAlertViewDele super.viewDidLoad() // Pause game when application enters background. - NotificationCenter.default.addObserver(self, - selector: #selector(ViewController.pauseGame), - name: UIApplication.didEnterBackgroundNotification, object: nil) + NotificationCenter.default.addObserver( + self, + selector: #selector(ViewController.pauseGame), + name: UIApplication.didEnterBackgroundNotification, object: nil) // Resume game when application becomes active. - NotificationCenter.default.addObserver(self, - selector: #selector(ViewController.resumeGame), - name: UIApplication.didBecomeActiveNotification, object: nil) + NotificationCenter.default.addObserver( + self, + selector: #selector(ViewController.resumeGame), + name: UIApplication.didBecomeActiveNotification, object: nil) startNewGame() } @@ -78,11 +80,12 @@ class ViewController: UIViewController, GADInterstitialDelegate, UIAlertViewDele timeLeft = ViewController.gameLength playAgainButton.isHidden = true updateTimeLeft() - timer = Timer.scheduledTimer(timeInterval: 1.0, - target: self, - selector:#selector(ViewController.decrementTimeLeft(_:)), - userInfo: nil, - repeats: true) + timer = Timer.scheduledTimer( + timeInterval: 1.0, + target: self, + selector: #selector(ViewController.decrementTimeLeft(_:)), + userInfo: nil, + repeats: true) } fileprivate func createAndLoadInterstitial() { @@ -134,10 +137,26 @@ class ViewController: UIViewController, GADInterstitialDelegate, UIAlertViewDele timer?.invalidate() timer = nil - UIAlertView(title: "Game Over", - message: "You lasted \(ViewController.gameLength) seconds", - delegate: self, - cancelButtonTitle: "Ok").show() + let alert = UIAlertController( + title: "Game Over", + message: "You lasted \(ViewController.gameLength) seconds", + preferredStyle: .alert) + let alertAction = UIAlertAction( + title: "OK", + style: .cancel, + handler: { [weak self] action in + guard let self = self else { + return + } + if self.interstitial.isReady { + self.interstitial.present(fromRootViewController: self) + } else { + print("Ad wasn't ready") + } + self.playAgainButton.isHidden = false + }) + alert.addAction(alertAction) + self.present(alert, animated: true, completion: nil) } // MARK: - Interstitial Button Actions @@ -146,24 +165,15 @@ class ViewController: UIViewController, GADInterstitialDelegate, UIAlertViewDele startNewGame() } - // MARK: - UIAlertViewDelegate - - func alertView(_ alertView: UIAlertView, willDismissWithButtonIndex buttonIndex: Int) { - if interstitial.isReady { - interstitial.present(fromRootViewController: self) - } else { - print("Ad wasn't ready") - } - playAgainButton.isHidden = false - } - // MARK: - deinit deinit { - NotificationCenter.default.removeObserver(self, - name: UIApplication.didEnterBackgroundNotification, object: nil) - NotificationCenter.default.removeObserver(self, - name: UIApplication.didBecomeActiveNotification, object: nil) + NotificationCenter.default.removeObserver( + self, + name: UIApplication.didEnterBackgroundNotification, object: nil) + NotificationCenter.default.removeObserver( + self, + name: UIApplication.didBecomeActiveNotification, object: nil) } } diff --git a/Swift/admanager/AdManagerInterstitialExample/Podfile.lock b/Swift/admanager/AdManagerInterstitialExample/Podfile.lock index 04e3b987..5289b96f 100644 --- a/Swift/admanager/AdManagerInterstitialExample/Podfile.lock +++ b/Swift/admanager/AdManagerInterstitialExample/Podfile.lock @@ -33,7 +33,7 @@ DEPENDENCIES: - Google-Mobile-Ads-SDK SPEC REPOS: - https://github.com/CocoaPods/Specs.git: + https://github.com/CocoaPods/Specs: - Google-Mobile-Ads-SDK - GoogleAppMeasurement - GoogleUtilities @@ -47,4 +47,4 @@ SPEC CHECKSUMS: PODFILE CHECKSUM: e8010867226962d070daa0ff42573f3cf3e62865 -COCOAPODS: 1.8.0 +COCOAPODS: 1.8.4 diff --git a/Swift/admanager/AdManagerRewardedVideoExample/AdManagerRewardedVideoExample/ViewController.swift b/Swift/admanager/AdManagerRewardedVideoExample/AdManagerRewardedVideoExample/ViewController.swift index 7e919952..966ae791 100644 --- a/Swift/admanager/AdManagerRewardedVideoExample/AdManagerRewardedVideoExample/ViewController.swift +++ b/Swift/admanager/AdManagerRewardedVideoExample/AdManagerRewardedVideoExample/ViewController.swift @@ -17,7 +17,7 @@ import GoogleMobileAds import UIKit -class ViewController: UIViewController, GADRewardedAdDelegate, UIAlertViewDelegate { +class ViewController: UIViewController, GADRewardedAdDelegate { enum GameState: NSInteger { case notStarted @@ -70,14 +70,16 @@ class ViewController: UIViewController, GADRewardedAdDelegate, UIAlertViewDelega coinCountLabel.text = "Coins: \(self.coinCount)" // Pause game when application is backgrounded. - NotificationCenter.default.addObserver(self, - selector: #selector(ViewController.applicationDidEnterBackground(_:)), - name: UIApplication.didEnterBackgroundNotification, object: nil) + NotificationCenter.default.addObserver( + self, + selector: #selector(ViewController.applicationDidEnterBackground(_:)), + name: UIApplication.didEnterBackgroundNotification, object: nil) // Resume game when application is returned to foreground. - NotificationCenter.default.addObserver(self, - selector: #selector(ViewController.applicationDidBecomeActive(_:)), - name: UIApplication.didBecomeActiveNotification, object: nil) + NotificationCenter.default.addObserver( + self, + selector: #selector(ViewController.applicationDidBecomeActive(_:)), + name: UIApplication.didBecomeActiveNotification, object: nil) startNewGame() } @@ -103,9 +105,10 @@ class ViewController: UIViewController, GADRewardedAdDelegate, UIAlertViewDelega } gameText.text = String(counter) - timer = Timer.scheduledTimer(timeInterval: 1.0, + timer = Timer.scheduledTimer( + timeInterval: 1.0, target: self, - selector:#selector(ViewController.timerFireMethod(_:)), + selector: #selector(ViewController.timerFireMethod(_:)), userInfo: nil, repeats: true) } @@ -166,21 +169,23 @@ class ViewController: UIViewController, GADRewardedAdDelegate, UIAlertViewDelega @IBAction func playAgain(_ sender: AnyObject) { if rewardedAd?.isReady == true { - rewardedAd?.present(fromRootViewController: self, delegate:self) + rewardedAd?.present(fromRootViewController: self, delegate: self) } else { - UIAlertView(title: "Rewarded video not ready", - message: "The rewarded video didn't finish loading or failed to load", - delegate: self, - cancelButtonTitle: "Drat").show() + 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 + self?.startNewGame() + }) + alert.addAction(alertAction) + self.present(alert, animated: true, completion: nil) } } - // MARK: UIAlertViewDelegate implementation - - func alertView(_ alertView: UIAlertView, willDismissWithButtonIndex buttonIndex: Int) { - startNewGame() - } - // MARK: GADRewardedAdDelegate func rewardedAd(_ rewardedAd: GADRewardedAd, userDidEarn reward: GADAdReward) { print("Reward received with currency: \(reward.type), amount \(reward.amount).") @@ -197,16 +202,26 @@ class ViewController: UIViewController, GADRewardedAdDelegate, UIAlertViewDelega } func rewardedAd(_ rewardedAd: GADRewardedAd, didFailToPresentWithError error: Error) { - UIAlertView(title: "Rewarded ad failed to present", - message: "The rewarded ad could not be presented.", - delegate: self, - cancelButtonTitle: "Drat").show() + let alert = UIAlertController( + title: "Rewarded ad failed to present", + message: "The reward ad could not be presented.", + preferredStyle: .alert) + let alertAction = UIAlertAction( + title: "Drat", + style: .cancel, + handler: { [weak self] action in + self?.startNewGame() + }) + alert.addAction(alertAction) + self.present(alert, animated: true, completion: nil) } deinit { - NotificationCenter.default.removeObserver(self, - name: UIApplication.didEnterBackgroundNotification, object: nil) - NotificationCenter.default.removeObserver(self, - name: UIApplication.didBecomeActiveNotification, object: nil) + NotificationCenter.default.removeObserver( + self, + name: UIApplication.didEnterBackgroundNotification, object: nil) + NotificationCenter.default.removeObserver( + self, + name: UIApplication.didBecomeActiveNotification, object: nil) } } diff --git a/Swift/admanager/AdManagerRewardedVideoExample/Podfile.lock b/Swift/admanager/AdManagerRewardedVideoExample/Podfile.lock index b8c1fe51..3ed1a704 100644 --- a/Swift/admanager/AdManagerRewardedVideoExample/Podfile.lock +++ b/Swift/admanager/AdManagerRewardedVideoExample/Podfile.lock @@ -33,7 +33,7 @@ DEPENDENCIES: - Google-Mobile-Ads-SDK SPEC REPOS: - https://github.com/CocoaPods/Specs.git: + https://github.com/CocoaPods/Specs: - Google-Mobile-Ads-SDK - GoogleAppMeasurement - GoogleUtilities @@ -47,4 +47,4 @@ SPEC CHECKSUMS: PODFILE CHECKSUM: 8440566f125d0e42ddc001b29dbe6b727aec861c -COCOAPODS: 1.8.0 +COCOAPODS: 1.8.4 diff --git a/Swift/admob/AdaptiveBannerExample/Podfile.lock b/Swift/admob/AdaptiveBannerExample/Podfile.lock index c57e2f8a..9fd9dbf8 100644 --- a/Swift/admob/AdaptiveBannerExample/Podfile.lock +++ b/Swift/admob/AdaptiveBannerExample/Podfile.lock @@ -33,7 +33,7 @@ DEPENDENCIES: - Google-Mobile-Ads-SDK SPEC REPOS: - https://github.com/CocoaPods/Specs.git: + https://github.com/CocoaPods/Specs: - Google-Mobile-Ads-SDK - GoogleAppMeasurement - GoogleUtilities @@ -47,4 +47,4 @@ SPEC CHECKSUMS: PODFILE CHECKSUM: 8fa1887f5400a75c87307feeb375a743ec3cb3b3 -COCOAPODS: 1.8.0 +COCOAPODS: 1.8.4 diff --git a/Swift/admob/BannerExample/Podfile.lock b/Swift/admob/BannerExample/Podfile.lock index adc3d262..ecc973b2 100644 --- a/Swift/admob/BannerExample/Podfile.lock +++ b/Swift/admob/BannerExample/Podfile.lock @@ -33,7 +33,7 @@ DEPENDENCIES: - Google-Mobile-Ads-SDK SPEC REPOS: - https://github.com/CocoaPods/Specs.git: + https://github.com/CocoaPods/Specs: - Google-Mobile-Ads-SDK - GoogleAppMeasurement - GoogleUtilities @@ -47,4 +47,4 @@ SPEC CHECKSUMS: PODFILE CHECKSUM: 7f54549ef5e0156a58d0457c3dbaf520ed68ad7f -COCOAPODS: 1.8.0 +COCOAPODS: 1.8.4 diff --git a/Swift/admob/InterstitialExample/InterstitialExample/ViewController.swift b/Swift/admob/InterstitialExample/InterstitialExample/ViewController.swift index 937d4028..6015c5d6 100644 --- a/Swift/admob/InterstitialExample/InterstitialExample/ViewController.swift +++ b/Swift/admob/InterstitialExample/InterstitialExample/ViewController.swift @@ -17,7 +17,7 @@ import GoogleMobileAds import UIKit -class ViewController: UIViewController, UIAlertViewDelegate { +class ViewController: UIViewController { enum GameState: NSInteger { case notStarted @@ -57,14 +57,16 @@ class ViewController: UIViewController, UIAlertViewDelegate { super.viewDidLoad() // Pause game when application enters background. - NotificationCenter.default.addObserver(self, - selector: #selector(ViewController.pauseGame), - name: UIApplication.didEnterBackgroundNotification, object: nil) + NotificationCenter.default.addObserver( + self, + selector: #selector(ViewController.pauseGame), + name: UIApplication.didEnterBackgroundNotification, object: nil) // Resume game when application becomes active. - NotificationCenter.default.addObserver(self, - selector: #selector(ViewController.resumeGame), - name: UIApplication.didBecomeActiveNotification, object: nil) + NotificationCenter.default.addObserver( + self, + selector: #selector(ViewController.resumeGame), + name: UIApplication.didBecomeActiveNotification, object: nil) startNewGame() } @@ -78,11 +80,12 @@ class ViewController: UIViewController, UIAlertViewDelegate { timeLeft = ViewController.gameLength playAgainButton.isHidden = true updateTimeLeft() - timer = Timer.scheduledTimer(timeInterval: 1.0, - target: self, - selector:#selector(ViewController.decrementTimeLeft(_:)), - userInfo: nil, - repeats: true) + timer = Timer.scheduledTimer( + timeInterval: 1.0, + target: self, + selector: #selector(ViewController.decrementTimeLeft(_:)), + userInfo: nil, + repeats: true) } fileprivate func createAndLoadInterstitial() { @@ -90,7 +93,7 @@ class ViewController: UIViewController, UIAlertViewDelegate { let request = GADRequest() // Request test ads on devices you specify. Your test device ID is printed to the console when // an ad request is made. - request.testDevices = [ kGADSimulatorID as! String, "2077ef9a63d2b398840261c8221a0c9a" ] + request.testDevices = [kGADSimulatorID as! String, "2077ef9a63d2b398840261c8221a0c9a"] interstitial.load(request) } @@ -138,10 +141,26 @@ class ViewController: UIViewController, UIAlertViewDelegate { timer?.invalidate() timer = nil - UIAlertView(title: "Game Over", - message: "You lasted \(ViewController.gameLength) seconds", - delegate: self, - cancelButtonTitle: "Ok").show() + let alert = UIAlertController( + title: "Game Over", + message: "You lasted \(ViewController.gameLength) seconds", + preferredStyle: .alert) + let alertAction = UIAlertAction( + title: "OK", + style: .cancel, + handler: { [weak self] action in + guard let self = self else { + return + } + if self.interstitial.isReady { + self.interstitial.present(fromRootViewController: self) + } else { + print("Ad wasn't ready") + } + self.playAgainButton.isHidden = false + }) + alert.addAction(alertAction) + self.present(alert, animated: true, completion: nil) } // MARK: - Interstitial Button Actions @@ -150,24 +169,15 @@ class ViewController: UIViewController, UIAlertViewDelegate { startNewGame() } - // MARK: - UIAlertViewDelegate - - func alertView(_ alertView: UIAlertView, willDismissWithButtonIndex buttonIndex: Int) { - if interstitial.isReady { - interstitial.present(fromRootViewController: self) - } else { - print("Ad wasn't ready") - } - playAgainButton.isHidden = false - } - // MARK: - deinit deinit { - NotificationCenter.default.removeObserver(self, - name: UIApplication.didEnterBackgroundNotification, object: nil) - NotificationCenter.default.removeObserver(self, - name: UIApplication.didBecomeActiveNotification, object: nil) + NotificationCenter.default.removeObserver( + self, + name: UIApplication.didEnterBackgroundNotification, object: nil) + NotificationCenter.default.removeObserver( + self, + name: UIApplication.didBecomeActiveNotification, object: nil) } } diff --git a/Swift/advanced/APIDemo/APIDemo/AdManagerMultipleAdSizesViewController.swift b/Swift/advanced/APIDemo/APIDemo/AdManagerMultipleAdSizesViewController.swift index 24f081a9..b34442a7 100644 --- a/Swift/advanced/APIDemo/APIDemo/AdManagerMultipleAdSizesViewController.swift +++ b/Swift/advanced/APIDemo/APIDemo/AdManagerMultipleAdSizesViewController.swift @@ -44,24 +44,34 @@ class AdManagerMultipleAdSizesViewController: UIViewController, GADAdSizeDelegat bannerView.translatesAutoresizingMaskIntoConstraints = false // Layout constraints that align the banner view to the bottom center of the screen. - view.addConstraint(NSLayoutConstraint(item: bannerView, attribute: .bottom, relatedBy: .equal, - toItem: bottomLayoutGuide, attribute: .top, multiplier: 1, constant: 0)) - view.addConstraint(NSLayoutConstraint(item: bannerView, attribute: .centerX, relatedBy: .equal, - toItem: view, attribute: .centerX, multiplier: 1, constant: 0)) + view.addConstraint( + NSLayoutConstraint( + item: bannerView, attribute: .bottom, relatedBy: .equal, + toItem: bottomLayoutGuide, attribute: .top, multiplier: 1, constant: 0)) + view.addConstraint( + NSLayoutConstraint( + item: bannerView, attribute: .centerX, relatedBy: .equal, + toItem: view, attribute: .centerX, multiplier: 1, constant: 0)) } // MARK: - Actions /// Loads an ad. @IBAction func loadAd(_ sender: AnyObject) { - guard GADAdSizeCustomBannerSwitch.isOn || GADAdSizeBannerSwitch.isOn || - GADAdSizeMediumRectangleSwitch.isOn else { - let alert = UIAlertView(title: "Load Ad Error", - message: "Failed to load ad. Please select at least one ad size.", - delegate: self, - cancelButtonTitle: "OK") - alert.alertViewStyle = .default - alert.show() + guard + GADAdSizeCustomBannerSwitch.isOn || GADAdSizeBannerSwitch.isOn + || GADAdSizeMediumRectangleSwitch.isOn + else { + let alert = UIAlertController( + title: "Load Ad Error", + message: "Failed to load ad. Please select at least one ad size.", + preferredStyle: .alert) + let alertAction = UIAlertAction( + title: "OK", + style: .cancel, + handler: nil) + alert.addAction(alertAction) + self.present(alert, animated: true, completion: nil) return } diff --git a/Swift/advanced/APIDemo/APIDemo/AdManagerPPIDViewController.swift b/Swift/advanced/APIDemo/APIDemo/AdManagerPPIDViewController.swift index 74a5de4b..e355b8b8 100644 --- a/Swift/advanced/APIDemo/APIDemo/AdManagerPPIDViewController.swift +++ b/Swift/advanced/APIDemo/APIDemo/AdManagerPPIDViewController.swift @@ -12,10 +12,6 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. -// - -import GoogleMobileAds -import UIKit class AdManagerPPIDViewController: UIViewController { @@ -39,12 +35,16 @@ class AdManagerPPIDViewController: UIViewController { request.publisherProvidedID = generatePublisherProvidedIdentifierFromUsername(username) bannerView.load(request) } else { - let alert = UIAlertView(title: "Load Ad Error", - message: "Failed to load ad. Username is required", - delegate: self, - cancelButtonTitle: "OK") - alert.alertViewStyle = .default - alert.show() + let alert = UIAlertController( + title: "Load Ad Error", + message: "Failed to load ad. Username is required", + preferredStyle: .alert) + let alertAction = UIAlertAction( + title: "OK", + style: .cancel, + handler: nil) + alert.addAction(alertAction) + self.present(alert, animated: true, completion: nil) } } @@ -62,7 +62,8 @@ class AdManagerPPIDViewController: UIViewController { let utf8Username = username.cString(using: String.Encoding.utf8) // Allocate memory for a byte array of unsigned characters with size equal to // CC_MD5_DIGEST_LENGTH. - let md5Buffer = UnsafeMutablePointer.allocate(capacity: Int(CC_MD5_DIGEST_LENGTH)) + let md5Buffer = UnsafeMutablePointer.allocate( + capacity: Int(CC_MD5_DIGEST_LENGTH)) // Create the 16 byte MD5 hash value. CC_MD5(utf8Username!, CC_LONG(strlen(utf8Username!)), md5Buffer) // Convert the MD5 hash value to an NSString of hex values. diff --git a/Swift/advanced/APIDemo/APIDemo/SimpleNativeAdView.swift b/Swift/advanced/APIDemo/APIDemo/SimpleNativeAdView.swift index 611909f1..0e130deb 100644 --- a/Swift/advanced/APIDemo/APIDemo/SimpleNativeAdView.swift +++ b/Swift/advanced/APIDemo/APIDemo/SimpleNativeAdView.swift @@ -27,56 +27,71 @@ private let SimpleNativeAdViewCaptionKey = "Caption" /// View representing a custom native ad format with template ID 10063170. class SimpleNativeAdView: UIView { - // Weak references to this ad's asset views. - @IBOutlet weak var headlineView: UILabel! - @IBOutlet weak var mainPlaceholder: UIView! - @IBOutlet weak var captionView: UILabel! + // Weak references to this ad's asset views. + @IBOutlet weak var headlineView: UILabel! - /// The custom native ad that populated this view. - var customNativeAd: GADNativeCustomTemplateAd? + @IBOutlet weak var mainPlaceholder: UIView! + @IBOutlet weak var captionView: UILabel! - override func awakeFromNib() { - super.awakeFromNib() - // Enable clicks on the headline. - headlineView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.performClickOnHeadline))) - headlineView.isUserInteractionEnabled = true - } + /// The custom native ad that populated this view. + var customNativeAd: GADNativeCustomTemplateAd? - @objc func performClickOnHeadline() { - customNativeAd?.performClickOnAsset(withKey: SimpleNativeAdViewHeadlineKey) - } + override func awakeFromNib() { + super.awakeFromNib() + // Enable clicks on the headline. + headlineView.addGestureRecognizer( + UITapGestureRecognizer(target: self, action: #selector(self.performClickOnHeadline))) + headlineView.isUserInteractionEnabled = true + } + + @objc func performClickOnHeadline() { + customNativeAd?.performClickOnAsset(withKey: SimpleNativeAdViewHeadlineKey) + } - /// Populates the ad view with the custom native ad object. - func populate(withCustomNativeAd customNativeAd: GADNativeCustomTemplateAd) { - self.customNativeAd = customNativeAd - // The custom click handler is an optional block which will override the normal click action - // defined by the ad. Pass nil for the click handler to let the SDK process the default click - // action. - customNativeAd.customClickHandler = { (_ assetID: String) -> Void in - UIAlertView(title: "Custom Click", message: "You just clicked on the headline!", delegate: nil, cancelButtonTitle: "OK", otherButtonTitles: "").show() - } - // Populate the custom native ad assets. - headlineView.text = customNativeAd.string(forKey: SimpleNativeAdViewHeadlineKey) - captionView.text = customNativeAd.string(forKey: SimpleNativeAdViewCaptionKey) - // Remove all the media placeholder's subviews. - for subview: UIView in mainPlaceholder.subviews { - subview.removeFromSuperview() - } - // This custom native ad has both a video and an image associated with it. We'll use the video - // asset if available, and otherwise fallback to the image asset. - var mainView: UIView! - if customNativeAd.videoController.hasVideoContent() { - mainView = customNativeAd.mediaView - } - else { - let image: UIImage? = customNativeAd.image(forKey: SimpleNativeAdViewMainImageKey)?.image - mainView = UIImageView(image: image) - } - mainPlaceholder.addSubview(mainView!) - // Size the media view to fill our container size. - mainView.translatesAutoresizingMaskIntoConstraints = false - let viewDictionary: [String:Any] = ["mainView":mainView] - mainPlaceholder.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[mainView]|", options: [], metrics: nil, views: viewDictionary)) - mainPlaceholder.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[mainView]|", options: [], metrics: nil, views: viewDictionary)) + /// Populates the ad view with the custom native ad object. + func populate(withCustomNativeAd customNativeAd: GADNativeCustomTemplateAd) { + self.customNativeAd = customNativeAd + // The custom click handler is an optional block which will override the normal click action + // defined by the ad. Pass nil for the click handler to let the SDK process the default click + // action. + customNativeAd.customClickHandler = { (_ assetID: String) -> Void in + let alert = UIAlertController( + title: "Custom Click", + message: "You just clicked on the headline!", + preferredStyle: .alert) + let alertAction = UIAlertAction( + title: "OK", + style: .cancel, + handler: nil) + alert.addAction(alertAction) + UIApplication.shared.keyWindow?.rootViewController?.present( + alert, animated: true, completion: nil) + } + // Populate the custom native ad assets. + headlineView.text = customNativeAd.string(forKey: SimpleNativeAdViewHeadlineKey) + captionView.text = customNativeAd.string(forKey: SimpleNativeAdViewCaptionKey) + // Remove all the media placeholder's subviews. + for subview:UIView in mainPlaceholder.subviews { + subview.removeFromSuperview() + } + // This custom native ad has both a video and an image associated with it. We'll use the video + // asset if available, and otherwise fallback to the image asset. + var mainView: UIView! + if customNativeAd.videoController.hasVideoContent() { + mainView = customNativeAd.mediaView + } else { + let image: UIImage? = customNativeAd.image(forKey: SimpleNativeAdViewMainImageKey)?.image + mainView = UIImageView(image: image) } + mainPlaceholder.addSubview(mainView!) + // Size the media view to fill our container size. + mainView.translatesAutoresizingMaskIntoConstraints = false + let viewDictionary: [String: Any] = ["mainView": mainView] + mainPlaceholder.addConstraints( + NSLayoutConstraint.constraints( + withVisualFormat: "H:|[mainView]|", options: [], metrics: nil, views: viewDictionary)) + mainPlaceholder.addConstraints( + NSLayoutConstraint.constraints( + withVisualFormat: "V:|[mainView]|", options: [], metrics: nil, views: viewDictionary)) + } } diff --git a/Swift/advanced/APIDemo/Podfile.lock b/Swift/advanced/APIDemo/Podfile.lock index 7e5d429f..1ff30901 100644 --- a/Swift/advanced/APIDemo/Podfile.lock +++ b/Swift/advanced/APIDemo/Podfile.lock @@ -33,7 +33,7 @@ DEPENDENCIES: - Google-Mobile-Ads-SDK SPEC REPOS: - https://github.com/CocoaPods/Specs.git: + https://github.com/CocoaPods/Specs: - Google-Mobile-Ads-SDK - GoogleAppMeasurement - GoogleUtilities @@ -47,4 +47,4 @@ SPEC CHECKSUMS: PODFILE CHECKSUM: ebe6ceb325f54fd410c09716065523aa52b67674 -COCOAPODS: 1.8.0 +COCOAPODS: 1.8.4