Xamarin.iOS Alerts Display Modal Alert Dialog

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

It was common practice to use NSRunLoop to show modal UIAlertView to block code execution until user input is processed in iOS; until Apple released the iOS7, it broke few existing apps. Fortunately, there is a better way of implementing it with C#’s async/await.

Here’s the new code taking advantage of async/await pattern to show modal UIAlertView:

Task ShowModalAletViewAsync (string title, string message, params string[] buttons)
{
    var alertView = new UIAlertView (title, message, null, null, buttons);
    alertView.Show ();
    var tsc = new TaskCompletionSource ();

    alertView.Clicked += (sender, buttonArgs) => {
        Console.WriteLine ("User clicked on {0}", buttonArgs.ButtonIndex);
        tsc.TrySetResult(buttonArgs.ButtonIndex);
    };
    return tsc.Task;
}

//Usage
async Task PromptUser() {
    var result = await ShowModalAletViewAsync 
               ("Alert", "Do you want to continue?", "Yes", "No"); //process the result
}


Got any Xamarin.iOS Question?