Xamarin.ios native ads admob

254 Views Asked by At

I have been trying to figure out how to implement native google ads (admob) in my Xamarin.iOS app. (not xamarin forms)

I have googled like crazy but can't find any good examples.

Does anyone have any code that they could share?

This is my code so far, but the adloader.delegate is always null..

public partial class ExploreController : UIViewController
{
        readonly AdLoader adLoader;

     public ExploreController (IntPtr handle) : base (handle)
     {
            adLoader = new AdLoader(
            "ca-app-pub-3940256099942544/3986624511",
            this,
            new AdLoaderAdType[] { AdLoaderAdType.Native },
            new AdLoaderOptions[] { new AdLoaderOptions() });

            adLoader.Delegate = new MyAdLoaderDelegate();
            var request = Request.GetDefaultRequest();
    }
}


public class MyAdLoaderDelegate : NSObject, IUnifiedNativeAdLoaderDelegate
{

    public MyAdLoaderDelegate()
    {
    }

    public void DidReceiveUnifiedNativeAd(AdLoader adLoader, NativeAd nativeAd)
    {
        Debug.WriteLine("DidReceiveUnifiedNativeAd");
    }
    public void DidFailToReceiveAd(AdLoader adLoader, NSError error)
    {
        Debug.WriteLine("DidFailToReceiveAd");
        //base.DidFailToReceiveAd(adLoader, error);
    }

    public void DidFinishLoading(AdLoader adLoader)
    {
        Debug.WriteLine("DidFinishLoading");
        //base.DidFinishLoading(adLoader);
    }
}
1

There are 1 best solutions below

0
On

This solution is for Xamarin iOS app with native Storyboard. This is NOT Xamarin Forms project.

  1. Install NuGet package Xamarin.Google.iOS.MobileAds (the latest)

  2. You should have UIView for the banner, with all needed constrains (you edit Storyboard files in XCode):

The C# code - in VS.

  1. Custom Class must be set to GADBannerView:

Set Custom Class for the banner in XCode

NOTE: You are using native name GADBannerView in Storyboard, while in C# you reference to the same class as just BannerView.

  1. You also need an outlet so you can reference the banner instance from C# code:

Outlet in XCode

    [Outlet]
    [GeneratedCode ("iOS Designer", "1.0")]
    BannerView bottomBanner { get; set; }
  1. Now you should be able to reference your native AdMob banner from C# code. This is how you may load the ad:

     public void ShowBannerAd()
     {
    
         bottomBanner.RootViewController = this;
    
         bottomBanner.AdSize = AdSizeCons.Banner;
    
         bottomBanner.AdUnitId = "<YOUR_AD_UNIT_ID>";
    
         var request = Request.GetDefaultRequest();
         bottomBanner.LoadRequest(request);
     }
    

The result:

AdMob ad in Simulator