All the tutorials on displaying ads on iOS are currently broken, as the package used to display ads has been removed.
There is a new package, however the usage example it gives is for an iOS dependent project. It will not work/compile for use in Xamarin Forms
The approach is the same however, You are rendering a View you declare in your portable project
Install the correct ad package, it should look like this in Nuget Package Manager
Here is the view I created in my Xamarin Forms project.
namespace CanadianClassifiedsAlerter { public class AdMobView : View { public AdMobView() { } } }
In my iOS project, I created a ViewRenderer.
[assembly: ExportRenderer(typeof(AdMobView), typeof(AdMobRenderer))] namespace CanadianClassifiedsAlerter.iOS { public class AdMobRenderer : Xamarin.Forms.Platform.iOS.ViewRenderer { const string bannerId = "THISISWHEREMY_AD_IDGOES"; BannerView adView; bool viewOnScreen = false; protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.View> e) { base.OnElementChanged(e); // Setup your BannerView, review AdSizeCons class for more Ad sizes. adView = new BannerView(size: AdSizeCons.Banner, origin: new CGPoint(-10, 0)) { AdUnitID = bannerId, RootViewController = UIApplication.SharedApplication.Windows[0].RootViewController }; // Wire AdReceived event to know when the Ad is ready to be displayed adView.AdReceived += (object sender, EventArgs ea) => { viewOnScreen = true; }; adView.LoadRequest(Request.GetDefaultRequest()); base.SetNativeControl(adView); } } }
Now, after all is said and done to add it to my page, it’s this simple!
mainLayout.Children.Add(new AdMobView { WidthRequest = 320, HeightRequest = 50 });
Your end result should look like this
EDIT: Sample project files are here
Unused Canadian Classifieds Portable Project Files (Xamarin Forms).
I decided to use Xamarin.iOS instead for this project, so feel free to do whatever with those files.
EDIT: A user followed the advice from this article and got the following error…
“Foundation.MonoTouchException: Objective-C exception thrown. Name: NSInvalidArgumentException Reason: -[AppDelegate window]: unrecognized selector sent to instance 0x79aa9b10”
He override the Window with the following code and away it worked!
public override UIWindow Window { get { return UIApplication.SharedApplication.KeyWindow; } }