### Start Google Mobile Ads SDK (Swift) Source: https://developers.google.com/admob/ios/api/reference/Classes/GADMobileAds Initiate the Google Mobile Ads SDK. Call this early to reduce latency. The completion handler is called when setup is complete or times out. ```swift func startWithCompletionHandler(_ completionHandler: @escaping (InitializationStatus) -> Void) ``` -------------------------------- ### start() Source: https://developers.google.com/admob/ios/api/reference/Classes/GADMobileAds Starts the Google Mobile Ads SDK. This method should be called as early as possible in your app's lifecycle. ```APIDOC ## start() ### Description Starts the Google Mobile Ads SDK. This method should be called as early as possible in your app's lifecycle. ### Method Swift: `func start() async -> InitializationStatus` Objective-C: `- (void)startWithCompletionHandler: (nullable GADInitializationCompletionHandler)completionHandler;` ``` -------------------------------- ### Setting Valid Ad Sizes Example Source: https://developers.google.com/admob/ios/api/reference/Classes/GAMBannerView.html Example demonstrating how to set an array of valid ad sizes for a banner view using Objective-C. ```Objective-C NSArray *validSizes = @[ NSValueFromGADAdSize(GADAdSizeBanner), NSValueFromGADAdSize(GADAdSizeLargeBanner) ]; bannerView.validAdSizes = validSizes; ``` -------------------------------- ### Example Redirect Configuration Source: https://developers.google.com/admob/ios/app-ads This is an example of how to configure a redirect in firebase.json to send users to 'https://www.example.com' from the root URL. ```json "hosting": { ... "redirects": [ { "source": "/", "destination": "https://www.example.com", "type": 301 } ] } ``` -------------------------------- ### Install CocoaPods Dependencies Source: https://developers.google.com/admob/ios/eu-consent Run this command in your terminal after updating your Podfile to install the SDK. ```bash pod install --repo-update ``` -------------------------------- ### Example Rewarded SSV Callback URL Source: https://developers.google.com/admob/ios/ssv This example shows a rewarded SSV callback URL with the content to be verified highlighted. The signature and key_id are the last two query parameters. ```text https://www.myserver.com/path?**ad_network=54...55&ad_unit=12345678&reward_amount=10&reward_item=coins ×tamp=150777823&transaction_id=12...DEF&user_id=1234567**&signature=ME...Z1c&key_id=1268887 ``` -------------------------------- ### Start Video with Unmuted Audio (Objective-C) Source: https://developers.google.com/admob/ios/native/options Use this snippet to configure the ad loader to start video ads with audio enabled. Set `startMuted` to `NO` on `GADVideoOptions`. ```objectivec GADVideoOptions *videoOptions = [[GADVideoOptions alloc] init]; videoOptions.startMuted = NO; self.adLoader = [[GADAdLoader alloc] initWithAdUnitID:"nativeAdUnitID" rootViewController:self adTypes:@[ GADAdLoaderAdTypeNative ] options:@[ videoOptions ]] ``` -------------------------------- ### Start Video with Unmuted Audio (Swift) Source: https://developers.google.com/admob/ios/native/options Use this snippet to configure the ad loader to start video ads with audio enabled. Set `shouldStartMuted` to `false` on `VideoOptions`. ```swift let videoOptions = VideoOptions() videoOptions.shouldStartMuted = false adLoader = AdLoader( adUnitID: "nativeAdUnitID", rootViewController: self, adTypes: [.native], options: [videoOptions]) ``` -------------------------------- ### Start Muted Option (Swift) Source: https://developers.google.com/admob/ios/api/reference/Classes/GADVideoOptions.html Configure whether videos should start muted in Swift. Defaults to YES. ```Swift var shouldStartMuted: Bool { get set } ``` -------------------------------- ### Install Pods Source: https://developers.google.com/admob/ios/crashlytics Install and update your project's pods using the CocoaPods package manager. This command ensures all dependencies are correctly set up. ```bash pod install --repo-update ``` -------------------------------- ### Start SDK Initialization Source: https://developers.google.com/admob/ios/api/reference/Classes/GADMobileAds Initializes the Google Mobile Ads SDK. This method can be called with or without a completion handler to track initialization status. ```swift func start() async -> InitializationStatus ``` -------------------------------- ### GADMediationAdapterSetUpCompletionBlock Swift Declaration Source: https://developers.google.com/admob/ios/api/reference/Type-Definitions Completion block executed when adapter setup is finished. It takes an optional error object. ```swift typealias GADMediationAdapterSetUpCompletionBlock = ((any Error)?) -> Void ``` -------------------------------- ### GADBannerView Source: https://developers.google.com/admob/ios/api/reference/Classes.html A view that displays banner ads. Refer to the AdMob iOS banner documentation to get started. ```APIDOC ## GADBannerView ### Description A view that displays banner ads. See https://developers.google.com/admob/ios/banner to get started. ### Declaration Swift ``` class BannerView : UIView ``` Objective-C ``` @interface GADBannerView : UIView ``` ``` -------------------------------- ### Set Up Adapter with Configuration Source: https://developers.google.com/admob/ios/api/reference/Protocols/GADMediationAdapter.html Asynchronously sets up the adapter's underlying ad network SDK. The completion handler is called when the adapter is ready to service ad requests or if an error occurs during setup. This method is optional and can be called on a background thread. ```Objective-C + (void)setUpWithConfiguration: (nonnull GADMediationServerConfiguration *)configuration completionHandler: (nonnull GADMediationAdapterSetUpCompletionBlock) completionHandler; ``` -------------------------------- ### Initialize Custom Event Adapter (Objective-C) Source: https://developers.google.com/admob/ios/custom-events/overview Implement the `setUpWithConfiguration:completionHandler:` method to initialize the SDK for your custom event. Call the completion handler upon successful initialization. ```objectivec #import "SampleCustomEvent.h" @implementation SampleCustomEvent + (void)setUpWithConfiguration:(nonnull GADMediationServerConfiguration *)configuration completionHandler:(nonnull GADMediationAdapterSetUpCompletionBlock)completionHandler { // This is where you initialize the SDK that this custom event is built // for. Upon finishing the SDK initialization, call the completion handler // with success. completionHandler(nil); } @end ``` -------------------------------- ### Initialize Custom Event Adapter (Swift) Source: https://developers.google.com/admob/ios/custom-events/overview Implement the `setUpWithConfiguration:completionHandler:` method to initialize the SDK for your custom event. Call the completion handler upon successful initialization. ```swift import GoogleMobileAds class SampleCustomEvent: NSObject, MediationAdapter { static func setUpWith( _ configuration: MediationServerConfiguration, completionHandler: @escaping GADMediationAdapterSetUpCompletionBlock ) { // This is where you will initialize the SDK that this custom event is built // for. Upon finishing the SDK initialization, call the completion handler // with success. completionHandler(nil) } } ``` -------------------------------- ### Start Muted Option (Objective-C) Source: https://developers.google.com/admob/ios/api/reference/Classes/GADVideoOptions.html Configure whether videos should start muted in Objective-C. Defaults to YES. ```Objective-C @property (nonatomic) BOOL startMuted; ``` -------------------------------- ### Initialize Firebase Project Source: https://developers.google.com/admob/ios/app-ads Run this command in your project's root directory to initialize Firebase. Follow the CLI prompts to set up Hosting and connect to your Firebase project. ```bash firebase init ``` -------------------------------- ### Notify Video Playback Start Source: https://developers.google.com/admob/ios/api/reference/Protocols/GADMediationNativeAdEventDelegate Use this method to notify the Google Mobile Ads SDK that the GADMediationAd has started video playback. ```swift func didPlayVideo() ``` ```objectivec - (void)didPlayVideo; ``` -------------------------------- ### WKWebView Delegate Setup and Click Handling Source: https://developers.google.com/admob/ios/browser/webview/click-behavior?hl=fr Set up WKWebView delegates and implement methods to intercept and handle navigation actions, determining whether to open URLs in SFSafariViewController or allow default behavior. ```Swift import GoogleMobileAds import SafariServices import WebKit class ViewController: UIViewController, WKNavigationDelegate, WKUIDelegate { override func viewDidLoad() { super.viewDidLoad() // ... Register the WKWebView. // 1. Set the WKUIDelegate on your WKWebView instance. webView.uiDelegate = self; // 2. Set the WKNavigationDelegate on your WKWebView instance. webView.navigationDelegate = self } // Implement the WKUIDelegate method. func webView( _ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? { // 3. Determine whether to optimize the behavior of the click URL. if didHandleClickBehavior( currentURL: webView.url, navigationAction: navigationAction) { print("URL opened in SFSafariViewController.") } return nil } // Implement the WKNavigationDelegate method. func webView( _ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) { // 3. Determine whether to optimize the behavior of the click URL. if didHandleClickBehavior( currentURL: webView.url, navigationAction: navigationAction) { return decisionHandler(.cancel) } decisionHandler(.allow) } // Implement a helper method to handle click behavior. func didHandleClickBehavior( currentURL: URL, navigationAction: WKNavigationAction) -> Bool { guard let targetURL = navigationAction.request.url else { return false } // Handle custom URL schemes such as itms-apps:// by attempting to // launch the corresponding application. if navigationAction.navigationType == .linkActivated { if let scheme = targetURL.scheme, !["http", "https"].contains(scheme) { UIApplication.shared.open(targetURL, options: [:], completionHandler: nil) return true } } guard let currentDomain = currentURL.host, let targetDomain = targetURL.host else { return false } // Check if the navigationType is a link with an href attribute or // if the target of the navigation is a new window. if (navigationAction.navigationType == .linkActivated || navigationAction.targetFrame == nil) && // If the current domain does not equal the target domain, // the assumption is the user is navigating away from the site. currentDomain != targetDomain { // 4. Open the URL in a SFSafariViewController. let safariViewController = SFSafariViewController(url: targetURL) present(safariViewController, animated: true) return true } return false } } ``` -------------------------------- ### -init Source: https://developers.google.com/admob/ios/privacy/api/reference/Classes/UMPConsentForm Unavailable initializer. Use +loadWithCompletionHandler: instead. ```APIDOC ## -init ### Description This initializer is unavailable. Use the `+loadWithCompletionHandler:` static method instead to create and load a consent form object. ### Method GET ### Endpoint `/consentForm/init` ### Parameters This method takes no parameters. ### Response This method is unavailable and will not return a response. ``` -------------------------------- ### present(from:) Source: https://developers.google.com/admob/ios/api/reference/Classes/GADAppOpenAd Presents the app open ad using the provided view controller. This method must be called on the main thread. If no view controller is provided, it attempts to present from the application's main window's top view controller. ```APIDOC ## present(from:) ### Description Presents the app open ad with the provided view controller. Must be called on the main thread. If rootViewController is nil, attempts to present from the top view controller of the application’s main window. ### Method Swift: `@MainActor func present(from rootViewController: UIViewController?)` Objective-C: `- (void)presentFromRootViewController:(nullable UIViewController *)rootViewController;` ``` -------------------------------- ### -init Source: https://developers.google.com/admob/ios/api/reference/Classes/GADSignalRequest Unavailable. Initialization is only available from a subclass. ```APIDOC ## -init ### Description Unavailable Initialization is only available from a subclass. ### Declaration #### Objective-C ```objc - (nonnull instancetype)init; ``` ``` -------------------------------- ### GADDisplayAdMeasurement Start Method Declaration Source: https://developers.google.com/admob/ios/api/reference/Classes/GADDisplayAdMeasurement.html Declaration for the `-startWithError:` method in Objective-C and `start()` in Swift. This method initiates OMID viewability measurement for display ads. ```swift func start() throws ``` ```objectivec - (BOOL)startWithError:(NSError *_Nullable *_Nullable)error; ``` -------------------------------- ### Add AppLovin Mediation Adapter (CocoaPods) Source: https://developers.google.com/admob/ios/mediation/applovin Add this line to your Podfile to include the AppLovin mediation adapter. Run 'pod install --repo-update' to install. ```ruby pod 'GoogleMobileAdsMediationAppLovin' ``` -------------------------------- ### Manual Integration of Pangle SDK and Adapter Source: https://developers.google.com/admob/ios/mediation/pangle For manual integration, download the latest Pangle SDK for iOS and link its framework files. Also, download the Pangle adapter and link 'PangleAdapter.xcframework'. ```bash # Download the latest Pangle SDK for iOS and link all .framework files. # Download the latest Pangle adapter from the Changelog and link PangleAdapter.xcframework. ``` -------------------------------- ### Lay out UIViews for Native Ads Source: https://developers.google.com/admob/ios/native/advanced This example shows how to set up the UIViews in Interface Builder to display native ad assets. Ensure the custom class for the main view is set to GADNativeAdView and for media views to GADMediaView. ```swift GADNativeAdView GADMediaView ``` -------------------------------- ### GADMediationAdapterSetUpCompletionBlock Source: https://developers.google.com/admob/ios/api/reference/Type-Definitions Executes when adapter set up completes. ```APIDOC ## GADMediationAdapterSetUpCompletionBlock ### Description Executes when adapter set up completes. ### Declaration Swift ```swift typealias GADMediationAdapterSetUpCompletionBlock = ((any Error)?) -> Void ``` Objective-C ```objc typedef void (^GADMediationAdapterSetUpCompletionBlock)(NSError *_Nullable); ``` ``` -------------------------------- ### Link Chartboost Frameworks (Manual Integration) Source: https://developers.google.com/admob/ios/mediation/chartboost For manual integration, download the Chartboost SDK and adapter. Link the required Chartboost frameworks and other necessary system frameworks into your Xcode project. ```bash Chartboost.framework ``` ```bash CHAMoatMobileAppKit.framework ``` ```bash ChartboostAdapter.framework ``` ```bash StoreKit ``` ```bash Foundation ``` ```bash CoreGraphics ``` ```bash WebKit ``` ```bash AVFoundation ``` ```bash UIKit ``` -------------------------------- ### Notify Video Start Source: https://developers.google.com/admob/ios/api/reference/Protocols/GADMediationRewardedAdEventDelegate Notifies Google Mobile Ads SDK that the GADMediationAd started video playback. Use this method to track the beginning of video ad playback. ```swift func didStartVideo() ``` ```objc - (void)didStartVideo; ``` -------------------------------- ### -presentFromRootViewController: Source: https://developers.google.com/admob/ios/api/reference/Classes/GADAppOpenAd Presents the app open ad from the provided root view controller. This method must be called on the main thread. ```APIDOC ## -presentFromRootViewController: ### Description Presents the app open ad from the provided root view controller. This method must be called on the main thread. ### Method Objective-C ### Endpoint N/A (SDK Method) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example Objective-C: ```objectivec NSError *error; if ([appOpenAd canPresentFromRootViewController:self error:&error]) { [appOpenAd presentFromRootViewController:self]; } else { NSLog(@"Cannot present ad: %@", error); } ``` ### Response N/A ``` -------------------------------- ### Example AdMob Public Keys JSON Source: https://developers.google.com/admob/ios/ssv This is an example of the JSON structure for AdMob public keys. It includes key IDs, PEM-encoded public keys, and Base64 encoded public keys. ```json { "keys": [ { keyId: 1916455855, pem: "-----BEGIN PUBLIC KEY-----\nMF...YTPcw==\n-----END PUBLIC KEY-----" base64: "MFkwEwYHKoZIzj0CAQYI...ltS4nzc9yjmhgVQOlmSS6unqvN9t8sqajRTPcw==" }, { keyId: 3901585526, pem: "-----BEGIN PUBLIC KEY-----\nMF...aDUsw==\n-----END PUBLIC KEY-----" base64: "MFYwEAYHKoZIzj0CAQYF...4akdWbWDCUrMMGIV27/3/e7UuKSEonjGvaDUsw==" }, ], } ``` -------------------------------- ### Initialize and Load WKWebView in Swift Source: https://developers.google.com/admob/ios/browser/webview Configure WKWebView for inline media playback and automatic video play. Load a network-based URL for optimized performance and correct cookie/URL handling. ```swift import WebKit var webview: WKWebview! class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Initialize a WKWebViewConfiguration object. let webViewConfiguration = WKWebViewConfiguration() // Let HTML videos with a "playsinline" attribute play inline. webViewConfiguration.allowsInlineMediaPlayback = true // Let HTML videos with an "autoplay" attribute play automatically. webViewConfiguration.mediaTypesRequiringUserActionForPlayback = [] // Initialize the WKWebView with your WKWebViewConfiguration object. webView = WKWebView(frame: view.frame, configuration: webViewConfiguration) view.addSubview(webView) // Load the URL for optimized web view performance. guard let url = URL(string: "https://google.github.io/webview-ads/test/") else { return } let request = URLRequest(url: url) webView.load(request) } } ``` -------------------------------- ### Add Maio CocoaPod Dependency Source: https://developers.google.com/admob/ios/mediation/maio Include this line in your project's Podfile to integrate the Maio mediation adapter using CocoaPods. Run 'pod install --repo-update' to install the pod. ```ruby pod 'GoogleMobileAdsMediationMaio' ``` -------------------------------- ### Initialize Google Mobile Ads SDK in Swift Source: https://developers.google.com/admob/ios/quick-start Call `MobileAds.shared.start()` as early as possible in your app's lifecycle to initialize the SDK. This is the recommended approach for Swift projects. ```swift // Initialize the Google Mobile Ads SDK. MobileAds.shared.start() ViewController.swift ``` -------------------------------- ### Add Meta Audience Network Pod (CocoaPods) Source: https://developers.google.com/admob/ios/mediation/facebook Include this line in your project's Podfile to integrate the Meta Audience Network adapter using CocoaPods. Run 'pod install --repo-update' to install the pod. ```ruby pod 'GoogleMobileAdsMediationFacebook' ``` -------------------------------- ### Initialize and Configure Native Ad Template Source: https://developers.google.com/admob/ios/native/templates This snippet shows how to import necessary template headers, initialize a template view, set it as the native ad view, add it to the view hierarchy, and optionally configure custom styles and constraints. ```Objective-C /// Step 1: Import the templates that you need. #import "NativeTemplates/GADTSmallTemplateView.h" #import "NativeTemplates/GADTTemplateView.h" ... // STEP 2: Initialize your template view object. GADTSmallTemplateView *templateView = [[NSBundle mainBundle] loadNibNamed:@"GADTSmallTemplateView" owner:nil options:nil] .firstObject; // STEP 3: Template views are just GADNativeAdViews. _nativeAdView = templateView; nativeAd.delegate = self; // STEP 4: Add your template as a subview of whichever view you'd like. // This must be done before calling addHorizontalConstraintsToSuperviewWidth. // Please note: Our template objects are subclasses of GADNativeAdView so // you can insert them into whatever type of view you’d like, and don’t need to // create your own. [self.view addSubview:templateView]; // STEP 5 (Optional): Create your styles dictionary. Set your styles dictionary // on the template property. A default dictionary is created for you if you do // not set this. Note - templates do not currently respect style changes in the // xib. NSString *myBlueColor = @"#5C84F0"; NSDictionary *styles = @{ GADTNativeTemplateStyleKeyCallToActionFont : [UIFont systemFontOfSize:15.0], GADTNativeTemplateStyleKeyCallToActionFontColor : UIColor.whiteColor, GADTNativeTemplateStyleKeyCallToActionBackgroundColor : [GADTTemplateView colorFromHexString:myBlueColor], GADTNativeTemplateStyleKeySecondaryFont : [UIFont systemFontOfSize:15.0], GADTNativeTemplateStyleKeySecondaryFontColor : UIColor.grayColor, GADTNativeTemplateStyleKeySecondaryBackgroundColor : UIColor.whiteColor, GADTNativeTemplateStyleKeyPrimaryFont : [UIFont systemFontOfSize:15.0], GADTNativeTemplateStyleKeyPrimaryFontColor : UIColor.blackColor, GADTNativeTemplateStyleKeyPrimaryBackgroundColor : UIColor.whiteColor, GADTNativeTemplateStyleKeyTertiaryFont : [UIFont systemFontOfSize:15.0], GADTNativeTemplateStyleKeyTertiaryFontColor : UIColor.grayColor, GADTNativeTemplateStyleKeyTertiaryBackgroundColor : UIColor.whiteColor, GADTNativeTemplateStyleKeyMainBackgroundColor : UIColor.whiteColor, GADTNativeTemplateStyleKeyCornerRadius : [NSNumber numberWithFloat:7.0], }; templateView.styles = styles; // STEP 6: Set the ad for your template to render. templateView.nativeAd = nativeAd; // STEP 7 (Optional): If you'd like your template view to span the width of your // superview call this method. [templateView addHorizontalConstraintsToSuperviewWidth]; [templateView addVerticalCenterConstraintToSuperview]; ``` -------------------------------- ### Initialize and Load WKWebView in Objective-C Source: https://developers.google.com/admob/ios/browser/webview Set up WKWebView for seamless video playback and automatic ad loading. Use a network URL to ensure proper functionality of cookies and page requests. ```objectivec @import WebKit; #import "ViewController.h" @interface ViewController () @property(nonatomic, strong) WKWebView *webView; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // Initialize a WKWebViewConfiguration object. WKWebViewConfiguration *webViewConfiguration = [[WKWebViewConfiguration alloc] init]; // Let HTML videos with a "playsinline" attribute play inline. webViewConfiguration.allowsInlineMediaPlayback = YES; // Let HTML videos with an "autoplay" attribute play automatically. webViewConfiguration.mediaTypesRequiringUserActionForPlayback = WKAudiovisualMediaTypeNone; // Initialize the WKWebView with your WKWebViewConfiguration object. self.webView = [[WKWebView alloc] initWithFrame:self.view.frame configuration:webViewConfiguration]; [self.view addSubview:self.webview]; // Load the URL for optimized web view performance. NSURL *url = [NSURL URLWithString:@"https://google.github.io/webview-ads/test/"]; NSURLRequest *request = [NSURLRequest requestWithURL:url]; [webView loadRequest:request]; } @end ``` -------------------------------- ### Add and Position Smart Banner (Objective-C) Source: https://developers.google.com/admob/ios/x-ad-rendering Adds a banner view to the main view and constrains it to the bottom, full-width. It handles safe area layout guides for iOS 11+ and falls back to using the bottom layout guide for older versions. ```objectivec - (void)addBannerViewToView:(UIView *)bannerView { bannerView.translatesAutoresizingMaskIntoConstraints = NO; [self.view addSubview:bannerView]; if (@available(ios 11.0, *)) { // In iOS 11, we need to constrain the view to the safe area. [self positionBannerViewFullWidthAtBottomOfSafeArea:bannerView]; } else { // In lower iOS versions, safe area is not available so we use // bottom layout guide and view edges. [self positionBannerViewFullWidthAtBottomOfView:bannerView]; } } #pragma mark - view positioning - (void)positionBannerViewFullWidthAtBottomOfSafeArea:(UIView *_Nonnull)bannerView NS_AVAILABLE_IOS(11.0) { // Position the banner. Stick it to the bottom of the Safe Area. // Make it constrained to the edges of the safe area. UILayoutGuide *guide = self.view.safeAreaLayoutGuide; [NSLayoutConstraint activateConstraints:@[ [guide.leftAnchor constraintEqualToAnchor:bannerView.leftAnchor], [guide.rightAnchor constraintEqualToAnchor:bannerView.rightAnchor], [guide.bottomAnchor constraintEqualToAnchor:bannerView.bottomAnchor] ]]; } - (void)positionBannerViewFullWidthAtBottomOfView:(UIView *_Nonnull)bannerView { [self.view addConstraint:[NSLayoutConstraint constraintWithItem:bannerView attribute:NSLayoutAttributeLeading relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeLeading multiplier:1 constant:0]]; [self.view addConstraint:[NSLayoutConstraint constraintWithItem:bannerView attribute:NSLayoutAttributeTrailing relatedBy:NSLayoutRelationEqual toItem:self.view ``` -------------------------------- ### Add and Position Smart Banner (Swift) Source: https://developers.google.com/admob/ios/x-ad-rendering Adds a banner view to the main view and constrains it to the bottom, full-width. It handles safe area layout guides for iOS 11+ and falls back to using the bottom layout guide for older versions. ```swift func addBannerViewToView(_ bannerView: BannerView) { bannerView.translatesAutoresizingMaskIntoConstraints = false view.addSubview(bannerView) if #available(iOS 11.0, *) { // In iOS 11, we need to constrain the view to the safe area. positionBannerViewFullWidthAtBottomOfSafeArea(bannerView) } else { // In lower iOS versions, safe area is not available so we use // bottom layout guide and view edges. positionBannerViewFullWidthAtBottomOfView(bannerView) } } // MARK: - view positioning @available (iOS 11, *) // func positionBannerViewFullWidthAtBottomOfSafeArea(_ bannerView: UIView) { // Position the banner. Stick it to the bottom of the Safe Area. // Make it constrained to the edges of the safe area. let guide = view.safeAreaLayoutGuide NSLayoutConstraint.activate([ guide.leftAnchor.constraint(equalTo: bannerView.leftAnchor), guide.rightAnchor.constraint(equalTo: bannerView.rightAnchor), guide.bottomAnchor.constraint(equalTo: bannerView.bottomAnchor) ]) } func positionBannerViewFullWidthAtBottomOfView(_ bannerView: UIView) { view.addConstraint(NSLayoutConstraint(item: bannerView, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .leading, multiplier: 1, constant: 0)) view.addConstraint(NSLayoutConstraint(item: bannerView, attribute: .trailing, relatedBy: .equal, toItem: view, attribute: .trailing, multiplier: 1, constant: 0)) view.addConstraint(NSLayoutConstraint(item: bannerView, attribute: .bottom, relatedBy: .equal, toItem: bottomLayoutGuide, attribute: .top, multiplier: 1, constant: 0)) } ``` -------------------------------- ### Initialize Google Mobile Ads SDK in Objective-C Source: https://developers.google.com/admob/ios/quick-start In Objective-C projects, initialize the SDK by calling `[GADMobileAds.sharedInstance startWithCompletionHandler:nil]`. This method should be invoked at the earliest opportunity. ```objectivec // Initialize the Google Mobile Ads SDK. [GADMobileAds.sharedInstance startWithCompletionHandler:nil]; ViewController.m ``` -------------------------------- ### Implement Rewarded Ad Loading (Swift) Source: https://developers.google.com/admob/ios/custom-events/rewarded Implement the `GADMediationRewardedAd` protocol to handle the actual loading of a rewarded ad. This Swift example shows how to initialize the ad network SDK with parameters from the ad configuration and set up the delegate. ```swift class SampleCustomEventRewarded: NSObject, MediationRewardedAd { /// The Sample Ad Network rewarded ad. var nativeAd: SampleRewarded? /// The ad event delegate to forward ad rendering events to Google Mobile Ads SDK. var delegate: MediationRewardedAdEventDelegate? /// Completion handler called after ad load. var completionHandler: GADMediationRewardedLoadCompletionHandler? func loadRewarded( for adConfiguration: MediationRewardedAdConfiguration, completionHandler: @escaping GADMediationRewardedLoadCompletionHandler ) { rewarded = SampleRewarded.init( adUnitID: adConfiguration.credentials.settings["parameter"] as? String) rewarded?.delegate = self let adRequest = SampleAdRequest() adRequest.testMode = adConfiguration.isTestRequest self.completionHandler = completionHandler rewarded?.fetchAd(adRequest) } } ``` -------------------------------- ### Get String from Version Number (Objective-C) Source: https://developers.google.com/admob/ios/api/reference/Functions Returns a string representation of the version number. ```objective-c extern NSString *_Nonnull GADGetStringFromVersionNumber(GADVersionNumber versionNumber) ``` -------------------------------- ### GADNativeAdImage Scale Property (Objective-C) Source: https://developers.google.com/admob/ios/api/reference/Classes/GADNativeAdImage.html Gets the scale factor of the native ad image. ```Objective-C @property (nonatomic, readonly) CGFloat scale; ``` -------------------------------- ### Initialization Source: https://developers.google.com/admob/ios/api/reference/Classes/GADBannerView.html Initializes and returns a banner view with the specified ad size placed at its superview’s origin. ```APIDOC ## -initWithAdSize: ### Description Initializes and returns a banner view with the specified ad size placed at its superview’s origin. ### Declaration Swift ```swift init(adSize: AdSize) ``` Objective-C ```objc - (nonnull instancetype)initWithAdSize:(GADAdSize)adSize; ``` ``` -------------------------------- ### GADNativeAdImage Scale Property (Swift) Source: https://developers.google.com/admob/ios/api/reference/Classes/GADNativeAdImage.html Gets the scale factor of the native ad image. ```Swift var scale: CGFloat { get } ``` -------------------------------- ### GADCustomEventParametersServer Source: https://developers.google.com/admob/ios/api/reference/Constants Key for getting the server parameter configured in AdMob when mediating to a custom event adapter. ```APIDOC ## GADCustomEventParametersServer ### Description Key for getting the server parameter configured in AdMob when mediating to a custom event adapter. Example: NSString *serverParameter = connector.credentials[GADCustomEventParametersServer]. ### Declaration Swift ``` let GADCustomEventParametersServer: String ``` Objective-C ``` extern NSString *const _Nonnull GADCustomEventParametersServer ``` ``` -------------------------------- ### Load URL in WKWebView (Objective-C) Source: https://developers.google.com/admob/ios/webview This Objective-C snippet demonstrates how to set up a WKWebView with media playback configurations and load a network URL. It's crucial to ensure the URL is correctly formatted. ```objectivec @import WebKit; #import "ViewController.h" @interface ViewController () @property(nonatomic, strong) WKWebView *webView; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // Initialize a WKWebViewConfiguration object. WKWebViewConfiguration *webViewConfiguration = [[WKWebViewConfiguration alloc] init]; // Let HTML videos with a "playsinline" attribute play inline. webViewConfiguration.allowsInlineMediaPlayback = YES; // Let HTML videos with an "autoplay" attribute play automatically. webViewConfiguration.mediaTypesRequiringUserActionForPlayback = WKAudiovisualMediaTypeNone; // Initialize the WKWebView with your WKWebViewConfiguration object. self.webView = [[WKWebView alloc] initWithFrame:self.view.frame configuration:webViewConfiguration]; [self.view addSubview:self.webview]; // Load the URL for optimized web view performance. NSURL *url = [NSURL URLWithString:@"https://google.github.io/webview-ads/test/"]; NSURLRequest *request = [NSURLRequest requestWithURL:url]; [webView loadRequest:request]; } ``` ``` -------------------------------- ### Get Error (Swift) Source: https://developers.google.com/admob/ios/api/reference/Classes/GADAdNetworkResponseInfo.html Retrieves the error associated with the request to the network. This property is optional and read-only. ```Swift var error: (any Error)? { get } ``` -------------------------------- ### Get Version String - Objective-C Source: https://developers.google.com/admob/ios/api/reference/Functions Use this Objective-C function to retrieve a string representation of a version number. ```objectivec NSString *_Nonnull GADGetStringFromVersionNumber(GADVersionNumber version) ``` -------------------------------- ### Get Version String - Swift Source: https://developers.google.com/admob/ios/api/reference/Functions Use this Swift function to retrieve a string representation of a version number. ```swift func string(for version: VersionNumber) -> String ``` -------------------------------- ### Initialize and Fetch Rewarded Ad Source: https://developers.google.com/admob/ios/custom-events/rewarded Initializes a SampleRewardedAd object and fetches an ad. Ensure the SampleRewardedAd class and delegate are properly set up. ```Objective-C #import "SampleRewardedAd.h" #import "SampleAdRequest.h" #import "SampleCustomEventUtils.h" // ... inside your custom event adapter class ... - (void)requestRewardedAdWithParameters:(nonnull NSDictionary *)serverParameters { NSString *adUnit = serverParameters[@"parameter"]; _rewardedAd = [[SampleRewardedAd alloc] initWithAdUnitID:adUnit]; _rewardedAd.delegate = self; SampleAdRequest *adRequest = [[SampleAdRequest alloc] init]; adRequest.testMode = NO; // Set based on your configuration [_rewardedAd fetchAd:adRequest]; } ``` -------------------------------- ### Get Video Duration Source: https://developers.google.com/admob/ios/api/reference/Protocols/GADMediatedUnifiedNativeAd.html Retrieves the duration of the video in seconds. Returns 0 if there is no video or the duration is unknown. ```Swift optional var duration: TimeInterval { get } ``` ```Objective-C @optional @property (nonatomic, readonly) NSTimeInterval duration; ``` -------------------------------- ### Deploy app-ads.txt to Firebase Hosting Source: https://developers.google.com/admob/ios/app-ads After placing the app-ads.txt file in the 'public' directory, use this command to deploy it to Firebase Hosting. Visit the provided URL to verify. ```bash firebase deploy --only hosting ``` -------------------------------- ### Start SDK Initialization with Completion Handler Source: https://developers.google.com/admob/ios/api/reference/Classes/GADMobileAds Initializes the Google Mobile Ads SDK and executes a completion handler upon completion. This is useful for performing actions after the SDK is ready. ```objective-c - (void)startWithCompletionHandler: (nullable GADInitializationCompletionHandler)completionHandler; ``` -------------------------------- ### Get Adapter Version Source: https://developers.google.com/admob/ios/api/reference/Protocols/GADMediationAdapter.html Returns the version number of the mediation adapter. This is useful for debugging and compatibility checks. ```Objective-C + (GADVersionNumber)adapterVersion; ``` -------------------------------- ### Get Publisher ID Source: https://developers.google.com/admob/ios/api/reference/Protocols/GADMediationAdRequest.html Retrieves the publisher ID set on the AdMob frontend. Available in Swift and Objective-C. ```Swift func publisherId() -> String? ``` ```Objective-C - (nullable NSString *)publisherId; ``` -------------------------------- ### Initialize Google Mobile Ads SDK and Check Adapter Status (Swift) Source: https://developers.google.com/admob/ios/mediate Initializes the Google Mobile Ads SDK and iterates through adapter statuses. This ensures all mediation adapters are ready before loading ads. ```swift MobileAds.shared.start { initializationStatus in // Check each adapter's initialization status. for (adapterName, status) in initializationStatus.adapterStatusesByClassName { print( "Adapter: \(adapterName), Description: \(status.description), Latency: \(status.latency)") } } ``` -------------------------------- ### Get a Default GADRequest Source: https://developers.google.com/admob/ios/api/reference/Classes/GADRequest.html Returns a default GADRequest object. This is the basic way to initialize an ad request. ```Objective-C + (nonnull instancetype)request; ``` -------------------------------- ### Initialize Google Mobile Ads SDK in SwiftUI Source: https://developers.google.com/admob/ios/quick-start For SwiftUI applications, use `MobileAds.shared.start()` to initialize the SDK. Ensure this is called early in your app's setup. ```swift // Initialize the Google Mobile Ads SDK. MobileAds.shared.start() GoogleMobileAdsConsentManager.swift ``` -------------------------------- ### Initialization Source: https://developers.google.com/admob/ios/api/reference/Classes/GADBannerView.html Initializes and returns a banner view with the specified ad size and origin relative to the banner’s superview. ```APIDOC ## -initWithAdSize:origin: ### Description Initializes and returns a banner view with the specified ad size and origin relative to the banner’s superview. ### Declaration Swift ```swift init(adSize: AdSize, origin: CGPoint) ``` Objective-C ```objc - (nonnull instancetype)initWithAdSize:(GADAdSize)adSize origin:(CGPoint)origin; ``` ``` -------------------------------- ### Get Response Info (Objective-C) Source: https://developers.google.com/admob/ios/api/reference/Classes/GADAppOpenAd Accesses information about the ad response that returned this ad. This property is read-only. ```objective-c @property (nonatomic, readonly, nonnull) GADResponseInfo *responseInfo; ``` -------------------------------- ### Click to Expand Option (Swift) Source: https://developers.google.com/admob/ios/api/reference/Classes/GADVideoOptions.html Enable click-to-expand behavior for videos in Swift. ```Swift var isClickToExpandRequested: Bool { get set } ``` -------------------------------- ### Get Response Info (Swift) Source: https://developers.google.com/admob/ios/api/reference/Classes/GADAppOpenAd Accesses information about the ad response that returned this ad. This property is read-only. ```swift var responseInfo: ResponseInfo { get } ``` -------------------------------- ### mediaContent Property Declaration (Objective-C) Source: https://developers.google.com/admob/ios/api/reference/Classes/GADMediaView.html This Objective-C declaration shows how to get and set the media content for a GADMediaView. ```objectivec @property (nonatomic, nullable) GADMediaContent *mediaContent; ``` -------------------------------- ### AppOpenAdManager Class (Swift) Source: https://developers.google.com/admob/ios/app-open Implement a singleton manager class to pre-load app open ads. This ensures an ad is ready when the user enters the app, providing a seamless experience. The manager handles loading, showing, and tracking the ad's lifecycle. ```swift class AppOpenAdManager: NSObject { /// The app open ad. var appOpenAd: AppOpenAd? /// Maintains a reference to the delegate. weak var appOpenAdManagerDelegate: AppOpenAdManagerDelegate? /// Keeps track of if an app open ad is loading. var isLoadingAd = false /// Keeps track of if an app open ad is showing. var isShowingAd = false /// Keeps track of the time when an app open ad was loaded to discard expired ad. var loadTime: Date? /// For more interval details, see https://support.google.com/admob/answer/9341964 let timeoutInterval: TimeInterval = 4 * 3_600 static let shared = AppOpenAdManager() AppOpenAdManager.swift ``` -------------------------------- ### mediaContent Property Declaration (Swift) Source: https://developers.google.com/admob/ios/api/reference/Classes/GADMediaView.html This Swift declaration shows how to get and set the media content for a GADMediaView. ```swift var mediaContent: MediaContent? { get set } ``` -------------------------------- ### Get All Extras (Objective-C) Source: https://developers.google.com/admob/ios/api/reference/Classes/GADCustomEventExtras Returns a dictionary containing all additional parameters currently set on the GADCustomEventExtras instance. ```objc - (nonnull NSDictionary *)allExtras; ``` -------------------------------- ### Get Ad Format (Objective-C) Source: https://developers.google.com/admob/ios/api/reference/Classes/GADMediationCredentials.html Retrieve the ad format associated with the credentials in Objective-C. This property is read-only. ```Objective-C @property (nonatomic, readonly) GADAdFormat format; ``` -------------------------------- ### Get All Extras (Swift) Source: https://developers.google.com/admob/ios/api/reference/Classes/GADCustomEventExtras Returns a dictionary containing all additional parameters currently set on the GADCustomEventExtras instance. ```swift func allExtras() -> [AnyHashable : Any] ``` -------------------------------- ### -canPresentFromRootViewController:error: Source: https://developers.google.com/admob/ios/api/reference/Classes/GADAppOpenAd Indicates whether the app open ad can be presented from the provided root view controller. This method must be called on the main thread. ```APIDOC ## -canPresentFromRootViewController:error: ### Description Indicates whether the app open ad can be presented from the provided root view controller. Must be called on the main thread. ### Method Objective-C ### Endpoint N/A (SDK Method) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example Objective-C: ```objectivec NSError *error; BOOL canPresent = [appOpenAd canPresentFromRootViewController:self error:&error]; if (canPresent) { // Ad can be presented } else { NSLog(@"Cannot present ad: %@", error); } ``` ### Response #### Success Response - **canPresent** (BOOL) - YES if the ad can be presented, NO otherwise. #### Response Example N/A ``` -------------------------------- ### Get Ad Format (Swift) Source: https://developers.google.com/admob/ios/api/reference/Classes/GADMediationCredentials.html Retrieve the ad format associated with the credentials in Swift. This property is read-only. ```Swift var format: AdFormat { get } ``` -------------------------------- ### Implement Rewarded Ad Loading (Objective-C) Source: https://developers.google.com/admob/ios/custom-events/rewarded Implement the `GADMediationRewardedAd` protocol to handle the actual loading of a rewarded ad. This Objective-C example demonstrates initializing the ad network SDK and managing the completion handler with atomic flags to prevent multiple calls. ```objective-c #import "SampleCustomEventRewarded.h" @interface SampleCustomEventRewarded () { /// The sample rewarded ad. SampleRewarded *_rewardedAd; /// The completion handler to call when the ad loading succeeds or fails. GADMediationRewardedLoadCompletionHandler _loadCompletionHandler; /// The ad event delegate to forward ad rendering events to Google Mobile Ads SDK. id _adEventDelegate; } @end - (void)loadRewardedAdForAdConfiguration:(GADMediationRewardedAdConfiguration *)adConfiguration completionHandler: (GADMediationRewardedLoadCompletionHandler)completionHandler { __block atomic_flag completionHandlerCalled = ATOMIC_FLAG_INIT; __block GADMediationRewardedLoadCompletionHandler originalCompletionHandler = [completionHandler copy]; _loadCompletionHandler = ^id( _Nullable id ad, NSError *_Nullable error) { // Only allow completion handler to be called once. if (atomic_flag_test_and_set(&completionHandlerCalled)) { return nil; } id delegate = nil; if (originalCompletionHandler) { // Call original handler and hold on to its return value. delegate = originalCompletionHandler(ad, error); } // Release reference to handler. Objects retained by the handler will also be released. originalCompletionHandler = nil; return delegate; }; } ``` -------------------------------- ### Get Error (Objective-C) Source: https://developers.google.com/admob/ios/api/reference/Classes/GADAdNetworkResponseInfo.html Retrieves the error associated with the request to the network. This property is optional (nullable) and read-only. ```Objective-C @property (nonatomic, readonly, nullable) NSError *error; ``` -------------------------------- ### Initialize Smart Banner Ad (Portrait) Source: https://developers.google.com/admob/ios/banner/smart Use `kGADAdSizeSmartBannerPortrait` to initialize a Smart Banner for portrait orientation. ```swift let bannerView = GADBannerView(adSize: kGADAdSizeSmartBannerPortrait) ``` -------------------------------- ### Present App Open Ad (Objective-C) Source: https://developers.google.com/admob/ios/api/reference/Classes/GADAppOpenAd Presents the app open ad with the provided view controller. If rootViewController is nil, it attempts to present from the top view controller of the application’s main window. Must be called on the main thread. ```objective-c - (void)presentFromRootViewController: (nullable UIViewController *)rootViewController; ``` -------------------------------- ### GADVideoController Source: https://developers.google.com/admob/ios/api/reference/Classes.html The video controller class provides a way to get the video metadata and also manages video content of the ad rendered by the Google Mobile Ads SDK. You don’t need to create an instance of this class. When the ad rendered by the Google Mobile Ads SDK loads video content, you may be able to get an instance of this class from the rendered ad object. ```APIDOC ## GADVideoController ### Description The video controller class provides a way to get the video metadata and also manages video content of the ad rendered by the Google Mobile Ads SDK. You don’t need to create an instance of this class. When the ad rendered by the Google Mobile Ads SDK loads video content, you may be able to get an instance of this class from the rendered ad object. ### Declaration Swift ``` class VideoController : NSObject ``` Objective-C ``` @interface GADVideoController : NSObject ``` ``` -------------------------------- ### Get Mediation Credentials Source: https://developers.google.com/admob/ios/api/reference/Protocols/GADMediationAdRequest.html Retrieves mediation configurations set by the publisher on the AdMob frontend. Available in Swift and Objective-C. ```Swift func credentials() -> [AnyHashable : Any]? ``` ```Objective-C - (nullable NSDictionary *)credentials; ``` -------------------------------- ### Access InitializationStatus (Swift) Source: https://developers.google.com/admob/ios/api/reference/Classes/GADMobileAds Retrieve the initialization status of ad networks integrated with the Google Mobile Ads SDK. ```swift var initializationStatus: InitializationStatus { get } ``` -------------------------------- ### Get Dictionary Representation Source: https://developers.google.com/admob/ios/api/reference/Classes/GADAdNetworkResponseInfo.html Provides a JSON-safe dictionary representation of the ad network response info. This is a read-only property. ```Objective-C @property (nonatomic, readonly, nonnull) NSDictionary *dictionaryRepresentation; ``` -------------------------------- ### Interstitial Ad Fetching Logic Source: https://developers.google.com/admob/ios/custom-events/interstitial This code snippet demonstrates the logic for fetching an interstitial ad using a sample SDK. It includes setting up the ad unit, creating a sample ad request, and initiating the ad fetch. The completion handler is managed to ensure it's called only once. ```objective-c #include "SampleInterstitial.h" #include "SampleAdRequest.h" #include "SampleCustomEventUtils.h" #include "GADMediationAdapter.h" #include // ... other code ... - (void)loadInterstitialAdForAdConfiguration: (GADMediationInterstitialAdConfiguration *)adConfiguration completionHandler: (GADMediationInterstitialLoadCompletionHandler _Nullable *_Nonnull)completionHandler { static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ originalCompletionHandler = completionHandler; }); // Only allow completion handler to be called once. if (atomic_flag_test_and_set(&completionHandlerCalled)) { return; } id delegate = nil; if (originalCompletionHandler) { // Call original handler and hold on to its return value. delegate = originalCompletionHandler(ad, error); } // Release reference to handler. Objects retained by the handler will also // be released. originalCompletionHandler = nil; return delegate; } NSString *adUnit = adConfiguration.credentials.settings[@"parameter"]; _interstitialAd = [[SampleInterstitial alloc] initWithAdUnitID:adUnit]; _interstitialAd.delegate = self; SampleAdRequest *adRequest = [[SampleAdRequest alloc] init]; adRequest.testMode = adConfiguration.isTestRequest; [_interstitialAd fetchAd:adRequest]; ``` -------------------------------- ### Get Ad Unit Mapping (Swift) Source: https://developers.google.com/admob/ios/api/reference/Classes/GADAdNetworkResponseInfo.html Retrieves the network configuration set on the AdMob UI. This property is read-only. ```Swift var adUnitMapping: [String : Any] { get } ``` -------------------------------- ### Load and Set FullScreenContentDelegate (Objective-C) Source: https://developers.google.com/admob/ios/migration This snippet demonstrates loading a rewarded ad and setting its full-screen content delegate. It includes delegate methods for handling ad presentation and dismissal. ```objectivec - (void)viewDidLoad { [super viewDidLoad]; GADRequest *request = [GADRequest request]; [GADRewardedAd loadWithAdUnitID:@"ca-app-pub-3940256099942544/1712485313" request:request completionHandler:^(GADRewardedAd *ad, NSError *error) { if (error) { NSLog(@"Rewarded ad failed to load with error: %@", [error localizedDescription]); return; } self.rewardedAd = ad; NSLog(@"Rewarded ad loaded."); self.rewardedAd.fullScreenContentDelegate = self; } /// Tells the delegate that the rewarded ad was presented. - (void)adDidPresentFullScreenContent:(id)ad { NSLog(@"Rewarded ad presented."); } /// Tells the delegate that the rewarded ad failed to present. - (void)ad:(id)ad didFailToPresentFullScreenContentWithError:(NSError *)error { NSLog(@"Rewarded ad failed to present with error: %@", [error localizedDescription]); } /// Tells the delegate that the rewarded ad was dismissed. - (void)adDidDismissFullScreenContent:(id)ad { NSLog(@"Rewarded ad dismissed."); } ``` -------------------------------- ### Initialize GADBannerView Programmatically (Swift) Source: https://developers.google.com/admob/ios/banner/anchored-adaptive Instantiate a GADBannerView and set up its constraints for programmatic placement. The ad size provides intrinsic content size, so explicit width/height constraints are not needed. ```swift // Initialize the banner view. bannerView = BannerView() bannerView.delegate = self bannerView.translatesAutoresizingMaskIntoConstraints = false view.addSubview(bannerView) // This example doesn't give width or height constraints, as the ad size gives the banner an // intrinsic content size to size the view. NSLayoutConstraint.activate([ // Align the banner's bottom edge with the safe area's bottom edge bannerView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor), // Center the banner horizontally in the view bannerView.centerXAnchor.constraint(equalTo: view.centerXAnchor), ]) BannerSnippets.swift ``` -------------------------------- ### GADMediationAdapterSetUpCompletionBlock Objective-C Declaration Source: https://developers.google.com/admob/ios/api/reference/Type-Definitions Completion block executed when adapter setup is finished. It takes an optional error object. ```objectivec typedef void (^GADMediationAdapterSetUpCompletionBlock)(NSError *_Nullable) ```