Category: Guide

Home / Category: Guide

Wouldn’t be nice if you could try your Xamarin.Forms iOS apps on your Apple device without using a Mac? Yes it would. And now you can!

Follow me and I’ll show you how to deploy your Xamarin.Forms iOS app on you Iphone or iPad without using a Mac thank to Xamarin Hot Restart!


To use Xamarin Hot Restart you need:

  • Visual Studio 2019 16.5 or higher
  • iTunes (64-bit, installed on your PC)
  • Apple Developer account and paid Apple Developer Program enrollment
  • Your Xamarin.Forms app for iOS

Do you have everything?

Let’s start having fun

Remember that Xamarin Hot Reload is still in preview so you will need to enable this feature in your Visual Studio.

To do it, go to Tools > Options > Environment > Preview Features > Enable Xamarin Hot Restart.

Enable Hot Reload

Enable it and remember to restart Visual Studio to actually enable it!


  • Set your iOS project as startup project
  • Set the build configuration to Debug – Iphone
  • In Configuration Manager enable “Deploy” for your iOS project
configuration manager
Enable deploy for iOS

Don’t connect your iPhone/iPad yet (the first time you have to configure this, then it doesn’t matter anymore)

Select “Local Device” and launch your app.

Now follow the instructions and if needed download and install iTunes.

After iTunes is installed, connect your iPhone/iPad to your pc.

Now you need to insert your Apple credentials and then enable the “Automatic provisioning“. This last step is not necessary but trust me, it’s very handy and your machine will automatically setup everything to run the app on your device.

Magic happened

If everything worked (if not you can write here a comment and I’ll try to help you) you will see your device listed among the available devices (where “Local Device” was). Now you can run your app on your local Apple device connected to your pc.

After installing your app on your device, Visual Studio will show a popup telling you to manually run the app. Do it and the popup will disappear and you will be able to test your app on your device.

Xamarin Hot Restart

Not only you can test your Xamarin.iOS app without a Mac, you can now even change your code in real time. After you have done your changes, you just need to press the restart button (next to the stop button on Visual Studio). Visual Studio will compile your changes and quickly relaunch your app. According to Microsoft These are the timing with the new Hot Restart:

Initial BuildInitial DeployIncremental BuildIncremental Deploy
Hot Restart19.49s22.66s2.24s3.89s
w/o Hot Restart163.38s11.24s41.40s8.12s

That’s quite impressive, and you have to consider that it’s just a preview so they can improve it.


  • The Hot Restart works only on Xamarin.Forms and iOS devices, only on a Visual Studio (They will add compatibility for Visual Studio for Mac later).
  • Only 64 bit devices are supported
  • Storyboard and Xib files are not supported
  • Static iOS libraries and frameworks are not supported (your app will crash)
  • You still need a Mac to publish your app on the App Store


Xamarin Hot Reload is just a preview but it’s already a great tool to use. We can now try our Xamarin.Forms app on our Apple devices without using a Mac. I tried it with the app I’m currently working on right now and I’m very impressed. I cannot use storyboards (I don’t) and the app crashed if I open Maps (it’s integrated in the app I’m creating) but other than that it works very well and I’m very excited to try it.

Try it yourself and write in the comments what do you think. If you need any help, leave a comment and I’ll reply asap.

Happy Coding! 🙂

Since ever, one of the most annoying problems of Xamarin Forms on Android was the start up time. A native app takes nothing while even the most basic Xamarin forms apps takes several seconds to show up on Android.

During the years Xamarin has tried hard to make things better, sometimes with very small improvements and other times with a bit better improvements but now with the new Visual Studio release (> 16.5) they did something amazing, something called Startup Tracing with custom Profiles.

Startup Tracing

I’m not going into many details here as the only thing that matters is how we can improve the performances of our Xamarin Forms apps for Android. So I’ll be very clear here. If you go into the Android Options of your Xamarin projects, you’ll see this:

If you enable the AOT Compilation (Ahead of time), your app performances will improve significantly and so the startup time, but your apk size will increase as well. At this point you can decide what is more important for you, performances or apk size.

Don’t answer yet, there is a solution

Since Visual Studio 2019 Version 16.2 you were able to enable the Startup Tracing. If you enable this option, the profiler will do its magic (memory, execution time and some stats) to create a profile for your app to increase the performances without affecting too much your apk size.

According to Xamarin (you can read the full post here), these are the results of enabling these options:

TypeStartup SpeedAPK Size
Normal2s914ms16.1 MB
AOT1s18ms34.6 MB
Startup Tracing1s518ms20.1 MB

It means that AOT is amazing and you should enable it but if you care about the apk size you should definitely enable the Startup tracing as well, so you’ll get an incredible startup speed improvement without affecting too much your apk size.

Amazing but now it’s even better

Since Visual Studio 16.5 (or Visual Studio for Mac 8.5), Xamarin did even better and trust me, the result is more than amazing. I was really impressed by it so do a favour to yourself and continue to read!

We can now generate a Custom Profile of our app! If we do that, the next time our app will run in no time (Cool cool cool cool cool…cit.).

Unfortunately for now there is no UI to generate a Custom Profile (hopefully Microsoft will do it soon), but I’ll show you how to generate your Custom Profile in no time. I’ll try to keep it as easy as I can and as usual, if you have questions or issues, leave a comment here and I’ll reply as soon as possible.

Generate a Custom Profile

Follow this short guide and you’ll get your Custom Profile in no time and you’ll really improve the performances of your Xamarin Forms apps for Android.

  • Open a command prompt in the directory that contains your Android *.csproj file.
  • Connect one (and only one) Android device to your computer.
  • In your Android manifest enable the INTERNET permission.
  • Write and run this command: msbuild /t:BuildAndStartAotProfiling
  • Run your app until is completely loaded (don’t press or do anything on your app!!!).
  • Write and run this command: msbuild /t:FinishAotProfiling (* if you have problems read just below these points)
  • This will create the file custom.aprof to your Android project. Now change the Build Action of this file to AndroidAotProfile.
  • Last step is to add two new properties to your Release configuration:

Enjoy your new amazing performances!

ONLY IN CASE OF ERROR: When running the command msbuild /t:FinishAotProfiling some people (I had it as well on one of my machines) get the error:

aotprofile-tool: Unable to read profile through local port: 9999

If you do, open the Command prompt with admin privileges and (always in the folder containing you Android .csproj file) write:

set PATH=%PATH%;"C:\Program Files (x86)\Android\android-sdk\platform-tools"
msbuild -t:FinishAotProfiling

This will solve the problem and you will be able to have your custom profile.

Again according to Xamarin (you can read it here) this is the result of their tests:

ReleaseRelease/AOTRelease/Startup Tracing (Default)Release/Startup Tracing(Custom)
Activity Displayed4863ms2086ms3655ms1900ms
APK Size48MB95MB57MB60MB


I’ve personally tried the Startup Tracing with Custom Profiles and trust me, the results are impressive, the first time i couldn’t believe my eyes. When we enable these options we can finally obtain startup performances very similar to a native app (similar, not the same…yet!) so may suggestion here is to enable AOT and Startup Tracing and to create a Custom Profile for every project you are going to create! My suggestion is add this page as preferite as you will need it for every project you are going to create. As usual, add a comment and I’ll try to reply asap!

There are many ways to write an app and many patterns to follow. Some are very useful, others a bit less but there is one that you should always use MVVM, Model View View Model. It allows you to separate your apps in three main parts or layers:

Model: Your data

View: Your UI

View Model: Your logic

This pattern is brilliant so you should really use it. In it, your View knows nothing about the logic of your app and your ViewModel knows nothing about the UI, but they communicate through a mechanism called Data Binding.

<Label Text="{Binding MyTitle}"/>

In this quick example we have associated the text property of our Label to the property “MyTitle” in our ViewModel. Easy, isn’t it?

The problem

MVVM is great (and you should really use it) BUT the data binding has two big problems:

  • Because they are resolved at run-time, you have no validation at compile-time. It means that if in the previous example, instead of MyTitle you write MyTile, you code will compile fine and you will be able to run your app BUT you will not see the text in your label.
  • As we said, they are resolved at run-time through a mechanism called reflection. Reflection is cool but it has an high overhead cost, so every time you load a page with some bindings, your app will consume time.

The solution

Luckily there is a solution to enjoy MVVM and Data Binding, without having to worry about performances and the solution is Compiled Bindings.

To enable the Compiled Binding you have to do two quick steps:

  • Enable XAML compilation.
  • Set the correct x:DataType attributes.

It’s incredibly easy to do it an it’s easier to do that to explain so I’m going to show you how to do it with an example.

If you are starting a new Xamarin.Forms project, the template already has the XAML compilation enabled, but if you need to enable it you can add this attribute:


to your page class in your XAML code behind. So the class of your page will be similatr to this:

[XamlCompilation (XamlCompilationOptions.Compile)]
public class HomePage : ContentPage
    //Add your content here...

Very easy. Now let’s see how to set the correct x:DataType.

First of all, let’s say that our View is called MyExamplePage and our ViewModel is called MyExampleViewModel and that our page has a label with a binding:

<ContentPage xmlns=""
        <viewModels:MyExampleViewModel />
            <Label Text="{Binding MyTitle}"
                HorizontalOptions="CenterAndExpand" />

This is a perfectly correct XAML and if we build and start it, it will run. If the property MyTitle exists in MyExampleViewModel, then we will be able to see the text.

Now let’s add the x:DataType  to enable the Compiled Data Binding. The code will be:

<ContentPage xmlns=""
        <viewModels:MyExampleViewModel />
            <Label Text="{Binding MyTitle}"
                HorizontalOptions="CenterAndExpand" />

the only thing we have added is:


I told you that it was easy.

Now we have obtained two great things:

  • Our code will be faster as we don’t have to use reflection anymore.
  • When we compile the code, the compiler will check if our properties (MyTitle in this case) are actually present in our ViewModel. If not, the compiler will inform you of the error and you will be able to quickly fix it.


I haven’t done any precise test but I’ve actually seen that enabling the Compiled Binding, made my app UI faster and smoother. So they work. Anywaythere are some numbers, According to Microsoft and Xamarin:

  • A  compiled binding with property-change notification is resolved approximately 8 times quicker than a classic binding.
  • A compiled binding without property-change notification is resolved approximately 20 times quicker than a classic binding.
  • Setting the BindingContext on a compiled binding that uses property change notification is approximately 5 times quicker than setting the BindingContext on a classic binding.
  • Setting the BindingContext on a compiled binding that doesn’t use property change notification is approximately 7 times quicker than setting the BindingContext on a classic binding.

Few Tips

  • Always use the Compiled Bindings
  • If possible, set the x:DataType attribute at the same level in the view hierarchy as the BindingContext is set. (When you set the BindingContext, set the x:DataType too)
  • The x:DataType attribute can be re-defined at any point in a view hierarchy. For example you can set the x:DataType at the ContentPage level (like we did before) and then set it again on a label or on a CollectionView (Really you should use them as I wrote here).
  • If for some reason in your view you need to disable the Compiled Bindings, you can set the x:DataType to null, for example:
<StackLayout x:DataType="{x:Null}">
    <Label Text="{Binding MyTitle}" />


Compiled Bindings are extremely useful for two main reasons, they are faster and they discover a lot of problems at compile-time. You should really always use them.

As usual, if you like the article or you have questions, leave a comment down here.

Every time we need to present a list of data in our apps, we use a component called ListView. This component does what we want but its performances are very bad, epsecially as it doesn’t support virtualization.

Luckily with Xamarin.Forms 4.3 we can now use a new component called CollectionView. It does exactly the same thing as a ListView but way better and with better performances.

I definitely suggest you to check your projects and replace your ListViews with the new shiny CollectionViews. I’ve done in in all my projects, it doesn’t require a lot of effort and the performances are definitely better. So do it! I’ll now show you how to do it. I’ve create a repository on GitHub with this example. You can find the link at the end of the post.

In the past we had ListViews…

Until version 4.3 to add a ListView we could add a code like this:

<ListView x:Name="MyListView"
           ItemsSource="{Binding MyItems}">
           <TextCell Text="{Binding Name}" />

What we have done is to add a ListView to our page called MyListView (naming an object is not mandatory as ideally using correctly MVVM you don’t have to use this name).

Then we have assigned some data to our list using the ItemsSource. MyItems is an ObservableCollection declared into the ViewModel associated.

After we have associated some Data to the ListView we have to show how they should appear. To do this, we can use the ItemTemplate property. There are standard DataTemplate that we can use with ListView and in this case we are going to use TextCell that is just a text. You can see it in the previous XAML code. Of course you can use all the other available DataTemplate or you can create every custom view you want. In the case of the previous XAML, the result is this:

ListView example
ListView example

…now we have CollectionViews

From Xamarin.Forms 4.3 we can now use the CollectionViews.

CollectionView is an improved component that will give you more control and better performances (much better performances).

There are few differences between ListView and CollectionView but most of the times, the transition from ListView to CollectionView is incredibly easy as we can see in the next XAML code. Here we are going to replace the ListView of the previous example with a CollectionView:

<CollectionView x:Name="MyCollectionView"
                ItemsSource="{Binding MyItems}">
            <Label Text="{Binding Name}" />

As you can see there are not many changes. First of all, you have to replace ListView with CollectionView. Same as for the ItemTemplate, replace ListView.ItemTemplate with CollectionView.ItemTemplate.

As you have probably noticed, there is a small difference. For the ListView as DataTemplate we used the TextCell, but this is not available anymore with CollectionViews so we have to write our own view. As we need to show only a text, what we can do is replace the TextCell with a Label.

//From this
<TextCell Text="{Binding Name}" />
//To this
<Label Text="{Binding Name}" />

Now let’s show how the page appears after these small changes:

CollectionView example
CollectionView example

As you can see graphically there are not many differences (but I’d say that the CollectionView appears nicer) but from a performances point of view, the differences are massive,e specially if you are going to add many items to your list.


I really encourage you to replace your ListViews with CollectionViews. It’s probably a matter of minutes but it will improve a lot the performances of your app.

The link for the example showed on this article is:

As usual if you have any questions, leave a comment and I’ll reply as soon as possible. And if you want more info about CollectionViews and its new features or MVVM (Model-View-ViewModel) let me know and I’ll add some post

Every good app needs to use a database. This database can be local (present in the app itself), or it can be remote (saved somewhere on the internet). The third option (fairly common) is to use both and then use a synchronisation mechanism between the two databases. In the case of a local database, the best possible option for our apps is to use an SQL database and use the SQLite library. This library can be used on mobile phones and PCs and is present on a multitude of different applications.

Use SQLite in Xamarin

In theory (I tell you later a better way) to add and use a SQL database in Xamarin.Forms you need to install the “sqlite-net-pcl” library in your projects (.netstandard, Android, iOS, UWP) and then create Dependencies Services (one for each platform).

The whole procedure is not particularly complicated, but it takes about half an hour. If you multiply half an hour for each project you are going to create, you will see that the amount of time lost becomes considerable.

After so many projects and many lost hours I decided to create and make available for everyone my library based on “sqlite-net-pcl“.

My library is called MtSql and allows you to add a SQL database to Xamarin apps in few seconds and in an extremely easy way. Going from 30 minutes to a few seconds is no small feat so I’ll explain how.


My library works with Xamarin and Windows, so you can use it in practically every project where you need to use a database. As this is a blog about Xamarin, I show you how it works on this platform.

Here are the steps to use a SQLite database in your Xamarin.Forms project.

  • Right click on your solution and select Manage Nuget Packages for Solution
  • Search for “MarcTron” (so you can see my other plugins too 🙂 ) or directly MTSql. Install MarcTron.Sqlite in your projects (.netstandard, Android, iOS, UWP).
  • Finished!!!! You have nothing else to do, right now you are ready to use a SQL database inside your app. Time taken: few seconds 🙂

How to use MTSQL

Now that the library is installed in your solution, we need to tell our app which database to use, so we need to establish a connection with the database. To do this we have several possibilities:

using MarcTron.Plugin;

SQLiteConnection conn = MtSql.Current.GetConnection("yourdbname.db3");

in this case we have established a connection with the “yourdbname.db3” database. If we want to create an asynchronous connection, we can instead write:

SQLiteAsyncConnection conn = MtSql.Current.GetConnectionAsync("yourdbname.db3");

Since version 1.2 of MTSql I have created an additional Helper to make everything even easier, so to establish the connection with your database, you can write:


PLEASE NOTE: You must always initialise the database with one of the three previous methods before using it.

In my library, to simplify your life, I’ve created a basic template for the tables in your database. This model is called BaseModel (I write it here just to show it to you):

public class BaseModel
    public string Id { get; set; }
    public DateTime CreatedAt { get; set; }
    public DateTime UpdatedAt { get; set; }

Using it is very simple. For example, if you have a table called User with a Name field, you can write the class that defines it as:

public class User : BaseModel
    public string Name{ get; set; }

Doing so your table will have not only the Name field but also a primary Id key and two CreatedAt, UpdatedAt dates, which specify when the data has been created and modified (very useful if you want to sort your tables by creation or update date).

The helper I created has inside a method called Save. This method will deal not only with inserting or updating a record within your tables but also creating a GUID for you (if you have not already created it) and updating the value of CreatedAt and UpdatedAt. FANTASTIC!

PLEASE NOTE: The Save method inserts an object if its primary key value is not present in the table while updating it if its value is already in the table.

You don’t have to use the BaseModel class but I suggest you to do so and now I’ll show you why.

An Example

Now let’s see a quick example to initialise the database, insert an object and then update it:


User user = new User() {Name = "Marco"};

user .Name = "Marco Troncone";

In the first line we have initialised the database (Don’t forget it, it is fundamental to do it).

We then created a User table using the User class written above. At this point we created a user and gave him the name Marco.

When we call the method


since user does not have an Id, the Save method will create one automatically (if you want you can assign one yourself) and will add the user to the table, setting CreatedAt and UpdatedAt to the current time.

At this point we try to change the user name and save the change:

user.Name = "Marco Troncone";

This time user has already an Id and this Id is already present in the table, this time the Save method will not add a new object to the table but will update the current object, automatically updating UpdatedAt. Easy right?

Thanks to the MTSql plugin, in exactly 6 lines of code we have initialised our database, created a table, added an object and modified an object.

Other methods inside the Helper

In the previous example, we’ve seen some helper methods (Initialise, CreateTable, Save), let’s see what the other methods we have:

//To insert a single item inside the table
Insert<TType>(TType item);

//To insert multiple items inside the table
InsertAll<TType>(IEnumerable<TType> items);

//To update an item inside the table
Update<TType>(TType item);

//To find an item inside the table
FirstOrDefault<TType>(Expression<Func<TType, bool>> expression);

//To get from the table the item with Id itemId
GetFromId<TType>(string itemId);

//To get from the table the items with parameter quals to value
GetBy<TType>(string parameter, object value);

//To get all the items from the table

//To delete the item from the table
Delete<TType>(TType item);

//To delete ALL the items from the table. WARNING!!!

//To see if an item exists
Exists<TType>(string itemId);

//To count the number of items in a table

The Helper I’ve created has all the main methods to work on your database. If some methods are not available, you can directly access the database (and therefore all its methods) using the command:


this is a direct link to the database connection and from here you can find all the supported methods.


Creating a database could be a complicated operation but thanks to the MTSql library, creating a database for our Xamarin projects. Forms is incredibly easy. Install the library from Nuget and in a few seconds and a few lines of code, you have a database ready to be used in your Android, iOS and UWP projects.

Do you have any doubts or suggestions? Add a comment below, and if the article and the library were helpful to you, share them.

Have you seen how amazing are the Admob Rewarded video Ads? If you are creating a game or an app, the Rewarded Videos are something you should add to your app.

UPDATE: I’ve added on github the source code of a project to test this Admob plugin. You can find it here:

Do you think that are difficult to implement and it takes hours of your time? WRONG!

Thanks to my plugin MarcTron.Admob ( you can add Rewarded Videos with a single line of code!!!

Exactly!!! Install the MarcTron.Admob free plugin and in less than few seconds you can show Rewarded Videos in your Android and iOS apps!

HOW (It’s super easy!!!)

  • Install the MarcTron.Admob plugin in your projects (.netstandard, Android and iOS).
  • That’s it! No other things to do!!!

Now, if you want to show a rewarded video you just have to write this code:


Of course remember to replace the xxx with your video ID that you can find on your Google Admob page.


We all love events 🙂 If you love them as well. There are 7 events that you can use with Rewarde Videos:

OnRewarded                          When the user gets a reward
OnRewardedVideoAdClosed             When the ads is closed
OnRewardedVideoAdFailedToLoad       When the ads fails to load
OnRewardedVideoAdLeftApplication    When the users leaves the application
OnRewardedVideoAdLoaded             When the ads is loaded
OnRewardedVideoAdOpened             When the ads is opened
OnRewardedVideoStarted              When the ads starts


We have just seen how to add Rewarded Videos (with the plugin you can add Banners and Interstitials as well) in less than few seconds.

Basically it’s a dream 🙂 But it’s all TRUE!


Now here some links that you can use:

A detailed tutorial on how to use the plugin:

The nuget package link:

The bitbucket project site to report/view issues:

Github test project to try the plugin:

Usually a desktop platform has a lot of available resources so many developers tend to avoid to improve the quality of their code.On a mobile platform the resources are quite limited and improving the code could make a huge difference. It can transform a slow and annoying app in a great fast and great one.Today, using the code I’ve written for one of my app Tv Series Time Manager, we are going to see how improving the code can make a huge difference in the loading time of your apps.


Improve your code – LINQ is your friend

Tv Series time manager allows you to keep track of your preferred tv series.It uses a public API to get information about all the TV Series created. As you can imagine there are thousands and thousands of Tv Series so we need to handle lists of thousands of items.Every time we launch the app, it searches online updated about the Tv Series you are following (new episodes, release dates, and so on). This can be a quite intensive task as the API we need to call returns a JSON file with more than 34000 items.The first time I’ve written the updated method I had this code:

var localTvShows = LocalData.GetAllTvShows(); 
var remoteUpdatedTime = await WsData.GetUpdatedShows(); 
foreach (var info in remoteUpdatedTime) 
    var show = localTvShows.FirstOrDefault(x => == info.Key); 
    if (show != null && info.Value > show.updated) 
        updateRequired = true; 

            if (UpdateRequired)
                foreach (var info in remoteUpdatedTime)
                    var show = localTvShows.FirstOrDefault(x => == info.Key);
                    if (show != null && info.Value > show.updated)
                        var remoteserie = await WsData.GetShow(;
                        SqlHelper.SyncSerie(show, remoteserie);
                        var episodeList = await WsData.GetEpisodes(;
                        SqlHelper.SyncEpisodes(show.idLocal, episodeList);

I load the local Tv Show followed by the user and the remote Tv Series with the corresponding update time.Inside the first foreach I check if I need to update the local Tv Series.In case I have to update a Tv Series, I use a second foreach to update every local TV Series inside the local Sql database. (To add SQLite database to your app, you can read this tutorial)The code worked pretty well but I wasn’t satisfied by the loading time so I started to look for a way to improve the performances and here I discovered once more that LINQ is our friend.

The new code with LINQ

I decided to use LINQ to evaluate if I have to update a tv series, so I’ve written the code replacing the old one with this:

var seriesToUpdate = from remoteTime in remoteUpdatedTime
                join localShow in localTvShows 
                    on remoteTime.Key equals
                where remoteTime.Key == && remoteTime.Value > localShow.updated
                select localShow;

            if (seriesToUpdate.Any())
                foreach (var show in seriesToUpdate)
                    var remoteserie = await WsData.GetShow(;
                    SqlHelper.SyncSerie(show, remoteserie);
                    var episodeList = await WsData.GetEpisodes(;
                    SqlHelper.SyncEpisodes(show.idLocal, episodeList);

Speed Test

Now it’s time to see if the new code is really better than the first (Obviously it is 🙂 ). To do so, I’ve divided the code in two parts.

  • Evaluate if an update is required (Part A)
  • Update the Tv Series (Part B).

To give you the idea of how much time we can save, I’ve enclosed both the code in a for statement repeating the it for 100 times. These are the result:

Part A

  • OLD CODE:  Elapsed Time: 1077 ms
  • NEW CODE: Elapsed Time:   225 ms

Part B

  • OLD CODE:  Elapsed Time:  590 ms
  • NEW CODE: Elapsed Time:   122 ms


  • OLD CODE:  Elapsed Time:  1667 ms
  • NEW CODE: Elapsed Time:    347 ms

Looking at the time spent by the old and new code we  went from 1667 ms to 347 ms, saving 1320 ms. The difference is HUGE.From the point of view of a user, saving almost 1.5 seconds makes a massive difference, maybe the difference between keeping your app or uninstalling it.


A mobile device has a limited amount of resources and users don’t like to spend time waiting in front of a loading screen. Even the most useful app, if not optimized will be uninstalled by the users. This is why it’s really important to optimize your code.Today we have seen that with a good use LINQ  we can massively reduce the time used by our code.If you like the article, comment and share it!

Admob for Xamarin made easy

May 6, 2019 | Guide, Plugin, Tutorial | 155 Comments

In this tutorial I’ll show you how to monetize your Xamarin apps with AdMob using my MTAdmob plugin.

Important: If you receive errors compiling the code for iOS, install the package Xamarin.Google.iOS.MobileAds in your iOS project.

UPDATE 16/10/2019: MTAdmob is now Open Source on Github: 11/10/2019: VERY IMPORTANT!!! The new version 1.4.4 is out. There is an issue in the latest Xamarin.Google.iOS.MobileAds 7.47. Because of this, in your iOS project you have to install the plugin Xamarin.Google.iOS.SignIn 4.4.0 too. This will let you compile and use MobileAds.

UPDATE 1/May/2019: I’ve released the new version 1.3 thas sovles some issues with iOS and improves performances.

UPDATE: From version 1.2, MTAdmob supports also Google ads rewarded videos for Android and iOS

UPDATE: I’ve added on github the source code of a project to test this Admob plugin. You can find it here:

To help you to speed up your Xamarin development, I’ve created a set of plugins, one of them is MTAdmob. Thanks to this plugin you can add Admob banners and Insterstitials in just few lines of code. It couldn’t be easier than that and I’ll show you.

Install the plugin

First of all, right click on your Xamarin solution and select “Manage Nuget packages for Solution”

manage nuget

Visual Studio will open a new screen where you can search and install one or more nuget packages. In this case we can search for the MTAdmob plugin. Searching for MarcTron will show you all my packages (I’m sure you can find other useful plugins that I’ve written), and we can select the MTAdmob plugin as showed in the next image.

It’s very important that you install the plugin in your PCL/.Net standard project and in your platform projects (Android, iOS, UWP).

After the Admob plugin is installed we can add banners and insterstitials to our projects.

Add Ads to our project

With version 1.0 the MTAdmob plugin supports banner and interstitials for Android and iOS. If you would like to see the plugin supporting also the UWP platform, let me now and I’ll add the support in a new version.

As I’ve said we can add Banners and Interstitials Admob ads to our project. Let’s start with the Banners

How to add an Admob Banner

An Admob banner is just a view inside our page. It means that we can add it using XAML or C#. First of all let’s see how to add an Admob banner using XAML.

Add an Admob Banner with XAML

In MTAdmob to use an Admob banner I’ve created a custom control called AdView, so to use it we can use this code:

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns=""

    <Label Text="Let's test an Admob Banner!" 
           VerticalOptions="CenterAndExpand" />
    <!-- Place the Admob controls here -->

In this example we have created a StackLayout with 2 controls: a label and an AdView (our Admob banner). Easy! Isn’t it???

The AdView control is basically a View so you can use all the properties you can think of like: HorizontalOptions, VerticalOptions, IsVisible…

In addition to these properties, I’ve added in AdView two other properties: AdsId and PersonalizedAds.

AdsId: Allows you to add the Banner Id (you can find it in your Admob account)

PersonalizedAds: This allow you to use non personalized ads. For example in case of GPDR. Of course it’s better to use personalized Ads.

To use these properties you can update the previous code to:

<controls:AdView PersonalizedAds="true" AdsId="xxxxxxxxxxxxxxxxxx"/>

Add an Admob Banner with C#

In case you don’t write your pages with XAML or you write your UI in C# or you want to add your view only in some cases, you can add your Admob Banner using this code:

using MarcTron.Plugin;
MTAdView ads = new MTAdView();

Of course you need to attach this View to your layout, but you know how to do it (If not, feel free to ask).

To use the custom properties you can change the previous code to:

MTAdView ads = new MTAdView();
ads.AdsId = "xxx";
ads.PersonalizedAds = true;

Also in this case, to add an Admob banner is INCREDIBILY EASY!!!

Global Custom Properties

As you have seen, the properties AdsId and PersonalizedAds belong to a single AdView. It means that you have to set them for every Admob Banner.

To make things even easier I’ve added the option to set these properties only once. To do so, you can use this C# code:

CrossMTAdmob.Current.UserPersonalizedAds = true;
CrossMTAdmob.Current.AdsId = "xxxxxxxxxxxxxxxx";

In this case all your Admob banner will show personalized ads and will have the same Id.

If you set local and global properties, the local ones will have higher priority.

Use of Banner Events

I’ve added 4 events to the Admob banner that you could find nice to have. These events are:

  • AdsClicked When a user clicks on the ads
  • AdsClosed When the user closes the ads
  • AdsImpression Called when an impression is recorded for an ad.
  • AdsOpened When the ads is opened

To use these events you can write this code:

AdView myAds = new AdView();
myAds.AdsClicked += MyAdsAdsClicked;
myAds.AdsClosed += MyAds_AdVClosed;
myAds.AdsImpression += MyAds_AdVImpression;
myAds.AdsOpened += MyAds_AdVOpened;

Of course you can use these events also if you have declared your AdView in your XAML code.

Admob Interstitials

Now that we know how to add Admob banners using my plugin MTAdmob, let’s see how we can add Admob Interstitials. If possible, to add an Admob interstitial is even easier. You just need a single line of code. Don’t you believe me? Look here how to show an Admob interstitial:


I told you!!! That’s it!!! With that line of code you have just showed an Interstitial in you app. Of course you need to replace that string with the Insterstitial ID you can find in your Admob account.

Events for Interstitials

There 3 events that you can use with Interstitials:

OnInterstitialLoaded        When it's loaded
OnInterstitialOpened        When it's opened      
OnInterstitialClosed        When it's closed

Rewarded Video

From version 1.1 the plugin supports the amazing Rewarded Video too.

To show a rewarded video you just need a single line of code:


Events for Rewarded videos

There are 7 events that you can use with the Rewarded video Ads:

OnRewarded                          When the user gets a reward
OnRewardedVideoAdClosed             When the ads is closed
OnRewardedVideoAdFailedToLoad       When the ads fails to load
OnRewardedVideoAdLeftApplication    When the users leaves the application
OnRewardedVideoAdLoaded             When the ads is loaded
OnRewardedVideoAdOpened             When the ads is opened
OnRewardedVideoStarted              When the ads starts


Before you can use the Admob banners and Interstitials, you need to initialize it. You need to do it only once so it makes sense to initialize it onside the OnCreate method in Android and FinishedLaunching in iOS.

In your Android project add this line in your OnCreate method:

MobileAds.Initialize(ApplicationContext, "ca-app-pub-xxxxxxxxxxxxxxxx~xxxxxxxxxx");

In your iOS project add this line in your FinishedLaunching method:


private void CompletionHandler(InitializationStatus status){}

In iOS you should install the package Xamarin.Google.iOS.MobileAds and Xamarin.Google.iOS.SignIn!

You need to add to your Info.plist file this:

	<string>YOUR APP ID</string>

Android Project (Important)

In your AndroidManifest you should add these lines:

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

<application android:label="Test.MTAdmob.Android">
    <meta-data android:name="" android:value="@integer/google_play_services_version"/>
    <meta-data android:name="" android:value="ca-app-pub-xxxxxxxxxxxxxxxx~yyyyyyyyyy"/>
    <activity android:name="" android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize" android:theme="@android:style/Theme.Translucent" />

iOS Project (Important)

From version 1.4.4 you need to manually install the packages: Xamarin.Google.iOS.MobileAds and Xamarin.Google.iOS.SignIn! If you don’t install them, your app will not compile.

Some useful links


This Admob MTAdmob plugin is incredibly easy to use but in case you need help, or you want to suggest a new feature or for any other reason, write me.

Android SDK Setup with Xamarin

May 4, 2019 | Guide | No Comments

As you know is very important to keep your system updated and this of course is valid for the Android SDK.You should alway use the lasted available Android components.The Official Xamarin Documentation is not very clear on how to configure properly the Android SDK, so here is what you should do to obtain the best from your Xamarin.Android projects.First of all you should really install the Xamarin Android SDK Manager instead of the classic SDK Manager.Probably the most important reason to do so is that since version 25.2.3 of the Android SDK Tools package, Google replaced the UI Manager with a command line utility. I really don’t know why, but I know that the Xamarin Android SDK Manager is a very good tool. So I really suggest you to download it.As stated in the official Xamarin website, the requirements are:

  • Visual Studio 2017 community edition or higher. Visual Studio 2017 version 15.5 or later is required. (I’ll suggest you to use the latest version 15.6)
  • Xamarin for Visual Studio version 4.5.0 or later.
  • Java Development Kit 8 (the JDK 9 is not supported yet inXamarin.Android)

The Xamarin Android SDK Manager is not compatible with Visual Studio 2015. You can add the Xamarin SDK Manager using the Visual Studio Installer: 

Visual Studio Installer
Install the Xamarin SDK Manager

Be sure to select the Xamarin SDK Manager and install it.If you launch again Visual Studio 2017 and click on Tools > Android > Android SDK Manager, the Xamarin Android SDK Manager will be launched instead of the Google Android SDK Manager.

Android sdk manager
Xamarin SDK Manager

Here there are two tabs: Platforms and Tools.


Inside the first Tab you can download and install the platforms you want to support. You don’t need to install all the platforms, you just need to install the most recent one and the lowest that you still want to support.So if you want to support the platforms from Android 4.1, just install the Android SDK Platform 16 (Android 4.1) and the Android SDK Platform 16 (Android Oreo 8.1).


From the Tools Tab, you should always try to update the tools to the latest version:

Android Tools
Use always the latest available tools

So you should install:

  • Android SDK Tools 26.1.1
  • Android SDK Platform-Tools 27.0.1
  • Android SDK Build-Tools 27.0.3

I also suggest you to install the Android emulator is case you want to try your app on multiple devices. The latest available version is:

  • Android Emulator 27.1.12

I’ll update this guide every time there will be an updated component so I suggest to bookmark/follow this page.

%d bloggers like this: