Putting iAds in a MonoGame game

An iAd shown in my game

Here is the code you need to add to Main.cs in you game to get iAds working. You don't need to add any unique IDs. The iAd SDK is able to work out what you app is by magic. Everything will work fine as long as your app is registered for iAds in iTunes Connect.

I call the method SetupAdvert at the end of FinishedLaunching in Main.cs:

private object _adBannerView;
private bool _advertPausedGame;

private void SetupAdvert()
{
    int width, height;
    var view = (game.Services.GetService(typeof(UIViewController)) as UIViewController).View;

    if (view.Bounds.Width <= 320)
    {
        width = 320;
        height = 50;
    }
    else
    {
        width = 768;
        height = 66;
    }

    var adSize = new NSString ("ADBannerContentSizePortrait");
    var advertX = view.Bounds.Height - height;

    _adBannerView = new ADBannerView();
    ADBannerView adBannerView = _adBannerView as ADBannerView;
    NSMutableSet nsM = new NSMutableSet();
    nsM.Add(adSize);
    adBannerView.RequiredContentSizeIdentifiers = nsM;
    adBannerView.CurrentContentSizeIdentifier = adSize;

    adBannerView.AdLoaded += new EventHandler(AdvertLoaded);
    adBannerView.FailedToReceiveAd += new EventHandler<AdErrorEventArgs>(AdvertFailedToReceiveAd);

    adBannerView.ActionShouldBegin = AdvertClicked;
    adBannerView.ActionFinished += new EventHandler (AdvertReturn);

    adBannerView.Frame = new RectangleF(0, advertX, width, height);
    adBannerView.Hidden = true;

    view.AddSubview (adBannerView);
}

void AdvertLoaded(object sender, EventArgs e)
{
    (_adBannerView as ADBannerView).Hidden = false;
}

void AdvertFailedToReceiveAd(object sender, AdErrorEventArgs e)
{
    (_adBannerView as ADBannerView).Hidden = true;
}

// Pauses the game while gamer is viewing advert
// Most methods called on Game you will need to implement yourself
bool AdvertClicked(ADBannerView banner, bool willLeaveApplication)
{
    if (game.IsActive && !game.IsPaused)
    {
        game.Pause ();
        _advertPausedGame = true;
    }
    else
    {
        _advertPausedGame = false;
    }

    return true;
}

// Resumes the game when gamer returns to your game
// You will need to implement Game.Resume yourself
void AdvertReturn(object sender, EventArgs e)
{
    if (_advertPausedGame)
    {
        game.Resume ();
    }
}

This code only deals with a portrait game. If you have any suggestions about how to improve it, then let me know in the comments.

No Comments