We are building a Xamarin.Forms Application and have Admob Ads in it. The Ads works fine on Simulator but gives a TypeInitializationException on IPhone 6s ios 13. The error is -
{System.TypeInitializationException: The type initializer for 'Google.MobileAds.AdSizeCons' threw an exception. ---> System.NullReferenceException: Object reference not set to an instance of an object. at Google.MobileAds.AdSizeCons.get_Banner () <0x114527170 + 0x00030> in <62f0bd410ddd4c31bdeb77ff27efb070>:0 at Google.MobileAds.AdSizeCons..cctor () <0x114526c60 + 0x00000> in <62f0bd410ddd4c31bdeb77ff27efb070>:0 --- End of inner exception stack trace ---
My code for Ads is -
AdView.cs
public class AdMobBannerAd : View
{
}
CustomRenderer.cs
[assembly: ExportRenderer(typeof(AdMobBannerAd), typeof(AdMobViewRenderer))]
namespace Excercise.iOS.Renderers {
[Protocol]
public class AdMobViewRenderer : ViewRenderer<AdMobBannerAd, BannerView>
{
string bannerId = "ca-app-pub-3940256099942544/2934735716"; // test ad id
BannerView adView;
// AdSize size = AdSize.SmartBanner;
bool viewOnScreen;
protected override void OnElementChanged(ElementChangedEventArgs<AdMobBannerAd> e)
{
base.OnElementChanged(e);
if (e.NewElement == null)
return;
if (e.OldElement == null)
{
adView = new BannerView(AdSizeCons.SmartBannerPortrait)
// adView = new BannerView()
{
AdUnitId = bannerId,
RootViewController = GetRootViewController()
};
//adView.AdSize = AdSizeCons.SmartBannerPortrait
// ;
adView.AdReceived += (sender, args) =>
{
if (!viewOnScreen) this.AddSubview(adView);
viewOnScreen = true;
};
var request = Request.GetDefaultRequest();
request.TestDevices = new[] { "xxxxxxx" };
// request.TestDevices =[];
adView.LoadRequest(request);
base.SetNativeControl(adView);
}
}
private UIViewController GetRootViewController()
{
foreach (UIWindow window in UIApplication.SharedApplication.Windows)
{
if (window.RootViewController != null)
{
return window.RootViewController;
}
}
return null;
}
AppDelegate.cs
public override bool FinishedLaunching(UIApplication app, NSDictionary options)
{
try
{
global::Xamarin.Forms.Forms.Init();
MobileAds.Configure("ca-app-pub-xxxxxxxxxxxx~xxxxxx");
App.ScreenHeight = (int)UIScreen.MainScreen.Bounds.Height;
App.ScreenWidth = (int)UIScreen.MainScreen.Bounds.Width;
LoadApplication(new App());
}
catch(Exception ex)
{
string str = ex.Message;
}
return base.FinishedLaunching(app, options);
}
Has anyone come across the same issue? Please help!
Thank you!
Change the order of: ... global::Xamarin.Forms.Forms.Init();
MobileAds.Configure("ca-app-pub-xxxxxxxxxxxx~xxxxxx"); ...
MobileAds need to come first.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.