Modal UIAlertView (iOS 7)

It’s common practice to use NSRunLoop to show modal UIAlertView to block code execution until user input is processed in iOS.

The below code worked perfectly on previous versions of iOS (5 & 6)

int ShowModalAletView (string title, string message, params string[] buttons)
{
    int clicked = -1;
    var alertView = new UIAlertView (title, message, null, null, buttons);
    alertView.Show ();
    bool done = false;
    alertView.Clicked += (sender, buttonArgs) => {
        Console.WriteLine ("User clicked on {0}", buttonArgs.ButtonIndex);
        clicked = buttonArgs.ButtonIndex;
    };
    while (clicked == -1){
        NSRunLoop.Current.RunUntil (NSDate.FromTimeIntervalSinceNow (0.5));
    }
    return clicked;
}

until Apple released the iOS7, it broke few existing apps 1. 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
}

  1. From Apple Developer Forum: https://devforums.apple.com/message/887792

Image Effects with Xamarin.Android

A while ago I was working on a sample app to demonstrate basic image editing abilities using ColorFilter to adjust an image brightness, contrast and saturation.

Color filters are great, but they are comparatively slow on large images, while looking for better options I learned that we could use Effects that are available in Android API Level 14

The effects in Android uses GPU and OpenGL textures to perform all the processing for maximum performances. The EffectFactory provides the list of various effects that can be applied to an image not just basic adjustments like brightness and contrast.

I have ported one of the Google’s sample to Xamarin.Android to demonstrate these effects, this should be a useful getting started sample for developers like me 🙂

The GitHub repository includes the full solution for the app in the screenshot if you want to run from it: monodroid-samples