### Load and Show Interstitial Ad Source: https://context7.com/googleads/googleads-mobile-ios-examples/llms.txt Implement interstitial ads, which are full-screen ads displayed at natural transition points in the app. This example demonstrates loading and presenting an interstitial ad. ```swift import GoogleMobileAds import UIKit class InterstitialViewController: UIViewController, FullScreenContentDelegate { var interstitialAd: InterstitialAd? override func viewDidLoad() { super.viewDidLoad() Task { await loadInterstitialAd() } } func loadInterstitialAd() async { do { interstitialAd = try await InterstitialAd.load( with: "ca-app-pub-3940256099942544/4411468910", // Test ad unit ID request: Request() ) interstitialAd?.fullScreenContentDelegate = self } catch { print("Failed to load interstitial ad: \(error.localizedDescription)") } } func showInterstitialAd() { if let ad = interstitialAd { ad.present(from: self) } else { print("Interstitial ad wasn't ready") } } // MARK: - FullScreenContentDelegate func adDidRecordImpression(_ ad: FullScreenPresentingAd) { print("Interstitial ad recorded an impression") } func adDidDismissFullScreenContent(_ ad: FullScreenPresentingAd) { print("Interstitial ad dismissed") interstitialAd = nil // Load the next ad Task { await loadInterstitialAd() } } func ad(_ ad: FullScreenPresentingAd, didFailToPresentFullScreenContentWithError error: Error) { print("Interstitial ad failed to present: \(error.localizedDescription)") interstitialAd = nil } } ``` -------------------------------- ### Load and Display Banner Ad Source: https://context7.com/googleads/googleads-mobile-ios-examples/llms.txt Implement banner ads, which are rectangular display ads occupying a portion of the app's layout. This example shows how to create, configure, and load an adaptive banner ad. ```swift import GoogleMobileAds import UIKit class BannerViewController: UIViewController, BannerViewDelegate { var bannerView: BannerView! override func viewDidLoad() { super.viewDidLoad() // Create and configure banner view bannerView = BannerView() bannerView.adUnitID = "ca-app-pub-3940256099942544/2435281174" // Test ad unit ID bannerView.rootViewController = self bannerView.delegate = self bannerView.translatesAutoresizingMaskIntoConstraints = false view.addSubview(bannerView) // Position banner at bottom of safe area NSLayoutConstraint.activate([ bannerView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor), bannerView.centerXAnchor.constraint(equalTo: view.centerXAnchor) ]) // Load an adaptive banner ad bannerView.adSize = largeAnchoredAdaptiveBanner(width: 375) bannerView.load(Request()) } // MARK: - BannerViewDelegate func bannerViewDidReceiveAd(_ bannerView: BannerView) { print("Banner ad loaded successfully") } func bannerView(_ bannerView: BannerView, didFailToReceiveAdWithError error: Error) { print("Banner ad failed to load: \(error.localizedDescription)") } func bannerViewDidRecordImpression(_ bannerView: BannerView) { print("Banner ad recorded an impression") } func bannerViewDidRecordClick(_ bannerView: BannerView) { print("Banner ad recorded a click") } } ``` -------------------------------- ### Implement Ad Manager Banner Ads Source: https://context7.com/googleads/googleads-mobile-ios-examples/llms.txt Integrate Ad Manager banner ads into your iOS application using `AdManagerBannerView` and `AdManagerRequest`. This example shows basic setup and ad loading. ```swift import GoogleMobileAds import UIKit class AdManagerBannerViewController: UIViewController, BannerViewDelegate { var bannerView: AdManagerBannerView! override func viewDidLoad() { super.viewDidLoad() bannerView = AdManagerBannerView() bannerView.adUnitID = "/21775744923/example/adaptive-banner" // Ad Manager ad unit bannerView.rootViewController = self bannerView.delegate = self view.addSubview(bannerView) loadBannerAd() } func loadBannerAd() { bannerView.adSize = largeAnchoredAdaptiveBanner(width: 375) bannerView.load(AdManagerRequest()) // Use AdManagerRequest instead of Request } func bannerViewDidReceiveAd(_ bannerView: BannerView) { print("Ad Manager banner loaded") } func bannerView(_ bannerView: BannerView, didFailToReceiveAdWithError error: Error) { print("Ad Manager banner failed: \(error.localizedDescription)") } } ``` -------------------------------- ### SwiftUI Integration for Banner Ads Source: https://context7.com/googleads/googleads-mobile-ios-examples/llms.txt Wrap `BannerView` using `UIViewRepresentable` to integrate banner ads into your SwiftUI application. This example demonstrates how to create a reusable banner view container. ```swift import GoogleMobileAds import SwiftUI struct BannerContentView: View { var body: some View { VStack { Spacer() let adSize = largeAnchoredAdaptiveBanner(width: 375) BannerViewContainer(adSize) .frame(width: adSize.size.width, height: adSize.size.height) } } } struct BannerViewContainer: UIViewRepresentable { let adSize: AdSize init(_ adSize: AdSize) { self.adSize = adSize } func makeUIView(context: Context) -> BannerView { let banner = BannerView(adSize: adSize) banner.adUnitID = "ca-app-pub-3940256099942544/2435281174" banner.delegate = context.coordinator banner.load(Request()) return banner } func updateUIView(_ uiView: BannerView, context: Context) {} func makeCoordinator() -> BannerCoordinator { BannerCoordinator(self) } class BannerCoordinator: NSObject, BannerViewDelegate { let parent: BannerViewContainer init(_ parent: BannerViewContainer) { self.parent = parent } func bannerViewDidReceiveAd(_ bannerView: BannerView) { print("SwiftUI banner loaded") } func bannerView(_ bannerView: BannerView, didFailToReceiveAdWithError error: Error) { print("SwiftUI banner failed: \(error.localizedDescription)") } } } ``` -------------------------------- ### Initialize Google Mobile Ads SDK Source: https://context7.com/googleads/googleads-mobile-ios-examples/llms.txt Call this once during app startup, after gathering user consent, to initialize the Google Mobile Ads SDK. ```swift import GoogleMobileAds class AppDelegate: UIResponder, UIApplicationDelegate { private var isMobileAdsStartCalled = false func startGoogleMobileAdsSDK() { DispatchQueue.main.async { guard !self.isMobileAdsStartCalled else { return } self.isMobileAdsStartCalled = true // Initialize the Google Mobile Ads SDK MobileAds.shared.start() } } } ``` -------------------------------- ### Implement App Open Ads Manager in Swift Source: https://context7.com/googleads/googleads-mobile-ios-examples/llms.txt Manages the loading and display of App Open Ads. Ensure the ad unit ID is correctly configured and handle ad lifecycle events. ```swift import GoogleMobileAds @MainActor protocol AppOpenAdManagerDelegate: AnyObject { func appOpenAdManagerAdDidComplete(_ appOpenAdManager: AppOpenAdManager) } @MainActor class AppOpenAdManager: NSObject, FullScreenContentDelegate { static let shared = AppOpenAdManager() var appOpenAd: AppOpenAd? weak var delegate: AppOpenAdManagerDelegate? var isLoadingAd = false var isShowingAd = false var loadTime: Date? let timeoutInterval: TimeInterval = 4 * 3600 // 4 hours private func isAdAvailable() -> Bool { guard let loadTime = loadTime else { return false } return appOpenAd != nil && Date().timeIntervalSince(loadTime) < timeoutInterval } func loadAd() async { guard !isLoadingAd && !isAdAvailable() else { return } isLoadingAd = true do { appOpenAd = try await AppOpenAd.load( with: "ca-app-pub-3940256099942544/5575463023", // Test ad unit ID request: Request() ) appOpenAd?.fullScreenContentDelegate = self loadTime = Date() } catch { print("App open ad failed to load: \(error.localizedDescription)") appOpenAd = nil loadTime = nil } isLoadingAd = false } func showAdIfAvailable() { guard !isShowingAd else { return } guard isAdAvailable(), let appOpenAd = appOpenAd else { delegate?.appOpenAdManagerAdDidComplete(self) Task { await loadAd() } return } appOpenAd.present(from: nil) isShowingAd = true } // MARK: - FullScreenContentDelegate func adDidDismissFullScreenContent(_ ad: FullScreenPresentingAd) { appOpenAd = nil isShowingAd = false delegate?.appOpenAdManagerAdDidComplete(self) Task { await loadAd() } } } ``` -------------------------------- ### Load and Show Rewarded Video Ad Source: https://context7.com/googleads/googleads-mobile-ios-examples/llms.txt Loads a Rewarded Video Ad and presents it to the user. Ensure the ad is loaded before attempting to show it. The reward is processed upon ad dismissal. ```swift import GoogleMobileAds import UIKit class RewardedAdViewController: UIViewController, FullScreenContentDelegate { var rewardedAd: RewardedAd? var coinCount = 0 override func viewDidLoad() { super.viewDidLoad() Task { await loadRewardedAd() } } func loadRewardedAd() async { do { rewardedAd = try await RewardedAd.load( with: "ca-app-pub-3940256099942544/1712485313", // Test ad unit ID request: Request() ) rewardedAd?.fullScreenContentDelegate = self } catch { print("Rewarded ad failed to load: \(error.localizedDescription)") } } func showRewardedAd() { guard let rewardedAd = rewardedAd else { print("Rewarded ad isn't available yet") return } rewardedAd.present(from: self) { let reward = rewardedAd.adReward print("Reward received: \(reward.amount) \(reward.type)") self.coinCount += reward.amount.intValue } } // MARK: - FullScreenContentDelegate func adDidDismissFullScreenContent(_ ad: FullScreenPresentingAd) { print("Rewarded ad dismissed") rewardedAd = nil Task { await loadRewardedAd() } } func ad(_ ad: FullScreenPresentingAd, didFailToPresentFullScreenContentWithError error: Error) { print("Rewarded ad failed to present: \(error.localizedDescription)") } } ``` -------------------------------- ### Configure Test Devices for Google Mobile Ads SDK Source: https://context7.com/googleads/googleads-mobile-ios-examples/llms.txt Add test device identifiers to ensure test ads are received during development. These identifiers can be found in console logs. ```swift import GoogleMobileAds class AdConfiguration { static func configureTestDevices() { // Add your test device identifiers (found in console logs) let testDeviceIdentifiers = ["2077ef9a63d2b398840261c8221a0c9b"] MobileAds.shared.requestConfiguration.testDeviceIdentifiers = testDeviceIdentifiers } static func disablePublisherFirstPartyID() { // Disables Publisher first-party ID for privacy MobileAds.shared.requestConfiguration.setPublisherFirstPartyIDEnabled(false) } } ``` -------------------------------- ### Implement Native Ads in Swift Source: https://context7.com/googleads/googleads-mobile-ios-examples/llms.txt Customizes the presentation of native ads to match your app's design. Requires a custom `NativeAdView` and handles ad loading and delegation. ```swift import GoogleMobileAds import UIKit class NativeAdViewController: UIViewController, AdLoaderDelegate, NativeAdLoaderDelegate, NativeAdDelegate { var adLoader: AdLoader! var nativeAdView: NativeAdView! override func viewDidLoad() { super.viewDidLoad() setupNativeAdView() loadNativeAd() } func setupNativeAdView() { // Load custom NativeAdView from xib guard let nibObjects = Bundle.main.loadNibNamed("NativeAdView", owner: nil), let adView = nibObjects.first as? NativeAdView else { return } nativeAdView = adView view.addSubview(nativeAdView) } func loadNativeAd() { adLoader = AdLoader( adUnitID: "ca-app-pub-3940256099942544/3986624511", // Test ad unit ID rootViewController: self, adTypes: [.native], options: nil ) adLoader.delegate = self adLoader.load(Request()) } // MARK: - NativeAdLoaderDelegate func adLoader(_ adLoader: AdLoader, didReceive nativeAd: NativeAd) { nativeAd.delegate = self // Populate the native ad view (nativeAdView.headlineView as? UILabel)?.text = nativeAd.headline nativeAdView.mediaView?.mediaContent = nativeAd.mediaContent (nativeAdView.bodyView as? UILabel)?.text = nativeAd.body (nativeAdView.callToActionView as? UIButton)?.setTitle(nativeAd.callToAction, for: .normal) (nativeAdView.iconView as? UIImageView)?.image = nativeAd.icon?.image (nativeAdView.advertiserView as? UILabel)?.text = nativeAd.advertiser // Associate the native ad with the view nativeAdView.nativeAd = nativeAd } func adLoader(_ adLoader: AdLoader, didFailToReceiveAdWithError error: Error) { print("Native ad failed to load: \(error.localizedDescription)") } // MARK: - NativeAdDelegate func nativeAdDidRecordImpression(_ nativeAd: NativeAd) { print("Native ad recorded impression") } func nativeAdDidRecordClick(_ nativeAd: NativeAd) { print("Native ad recorded click") } } ``` -------------------------------- ### Manage User Consent with UMP SDK Source: https://context7.com/googleads/googleads-mobile-ios-examples/llms.txt Implement user consent management for GDPR compliance using the User Messaging Platform (UMP) SDK. Ensure user privacy and ad personalization settings are handled correctly. ```swift import GoogleMobileAds import UserMessagingPlatform @MainActor class GoogleMobileAdsConsentManager: NSObject { static let shared = GoogleMobileAdsConsentManager() var canRequestAds: Bool { return ConsentInformation.shared.canRequestAds } var isPrivacyOptionsRequired: Bool { return ConsentInformation.shared.privacyOptionsRequirementStatus == .required } func gatherConsent( from viewController: UIViewController?, completion: @escaping @MainActor (Error?) -> Void ) { let parameters = RequestParameters() // For testing, simulate EEA geography // let debugSettings = DebugSettings() // debugSettings.geography = .EEA // parameters.debugSettings = debugSettings ConsentInformation.shared.requestConsentInfoUpdate(with: parameters) { error in guard error == nil else { Task { @MainActor in completion(error) } return } Task { @MainActor in do { try await ConsentForm.loadAndPresentIfRequired(from: viewController) completion(nil) } catch { completion(error) } } } } @MainActor func presentPrivacyOptionsForm(from viewController: UIViewController?) async throws { try await ConsentForm.presentPrivacyOptionsForm(from: viewController) } } ``` -------------------------------- ### Present Ad Inspector for Debugging Source: https://context7.com/googleads/googleads-mobile-ios-examples/llms.txt Use the Ad Inspector to test ad requests and troubleshoot integration issues directly on the device. This requires presenting the inspector from a view controller. ```swift import GoogleMobileAds import UIKit class AdInspectorViewController: UIViewController { @IBAction func openAdInspector(_ sender: Any) { Task { do { try await MobileAds.shared.presentAdInspector(from: self) } catch { let alert = UIAlertController( title: "Ad Inspector Error", message: error.localizedDescription, preferredStyle: .alert ) alert.addAction(UIAlertAction(title: "OK", style: .cancel)) present(alert, animated: true) } } } } ``` -------------------------------- ### Load and Show Rewarded Interstitial Ad Source: https://context7.com/googleads/googleads-mobile-ios-examples/llms.txt Loads a Rewarded Interstitial Ad and presents it. This ad type combines interstitial and rewarded features. It's crucial to load the ad before showing it and handle dismissal to reload. ```swift import GoogleMobileAds import UIKit class RewardedInterstitialViewController: UIViewController, FullScreenContentDelegate { var rewardedInterstitialAd: RewardedInterstitialAd? override func viewDidLoad() { super.viewDidLoad() Task { await loadRewardedInterstitialAd() } } func loadRewardedInterstitialAd() async { do { rewardedInterstitialAd = try await RewardedInterstitialAd.load( with: "ca-app-pub-3940256099942544/6978759866", // Test ad unit ID request: Request() ) rewardedInterstitialAd?.fullScreenContentDelegate = self } catch { print("Rewarded interstitial ad failed to load: \(error.localizedDescription)") } } func showRewardedInterstitialAd() { guard let ad = rewardedInterstitialAd else { print("Rewarded interstitial ad not ready") return } ad.present(from: self) { let reward = ad.adReward print("Reward received: \(reward.amount) \(reward.type)") } } // MARK: - FullScreenContentDelegate func adDidDismissFullScreenContent(_ ad: FullScreenPresentingAd) { rewardedInterstitialAd = nil Task { await loadRewardedInterstitialAd() } } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.