Awaitable ShowAlert

Alex Corrado shared with me a trick to easily show UIAlertViews without ceremony.

You use it like this:

async void Demo ()
    switch (await ShowAlert ("Title", "Message", "Ok", "Cancel")){
	case 0: // Ok
        case 1: // Cancel

The beauty is being able to show alerts and linearly decide what to do with the result.

Here is the helper method:

// Displays a UIAlertView and returns the index of the button pressed.
public static Task ShowAlert (string title,
                                   string message,
                                   params string [] buttons)
    var tcs = new TaskCompletionSource ();
    var alert = new UIAlertView {
        Title = title,
        Message = message
    foreach (var button in buttons)
        alert.AddButton (button);
    alert.Clicked += (s, e) => tcs.TrySetResult (e.ButtonIndex);
    alert.Show ();
    return tcs.Task;
Posted on 03 Oct 2013 by Miguel de Icaza
This is a personal web page. Things said here do not represent the position of my employer.