Last Updated: February 25, 2016
·
713
· oleggavrilov

Pro alerts in Xamarin.iOS

Since iOS does not have synchronous alerts, normally to receive user's input you had to attach handler to event "Clicked". But because Xamarin brought async magic to the iOS dinosaur, we can do this:

public Task<int> ShowCookCourseAlert()
{
    var tcs = new TaskCompletionSource<int>();

    UIApplication.SharedApplication.InvokeOnMainThread(new NSAction(() => {
        UIAlertView alert = new UIAlertView("title", "message", null, "Cancel","OK" );
        alert.Clicked += (sender, buttonArgs) => tcs.SetResult(buttonArgs.ButtonIndex);
        alert.Show();
    }));

    return tcs.Task;
}

And then use this method like this:

int choice = await ShowCookCourseAlert();
Debug.WriteLine(choice);