0

I want to programmatically tap the "Close" button on an error alert in my xamarin iOS app. To do this I need to execute the action associated with that button on the alert. I saw this post on how to do it in obj-c but I can't figure out how to do it in Xamarin C#. I tried doing this:

        Action closeButtonAction = Marshal.GetDelegateForFunctionPointer<Action>(AlertController.Alert.Actions[0].Handle);
        closeButtonAction();

but the Actions Target property was null so I got a NRE when trying to execute it.

Here's what the UIAlertAction looks like in the debugger:enter image description here

Casey Hancock
  • 508
  • 6
  • 19

1 Answers1

1

You can programmatically dismiss an UIAlertView via DismissWithClickedButtonIndex and then call the delegate via Delegate.Clicked.

Example of IUIAlertViewDelegate:

public class UIAlertViewDelegate : NSObject, IUIAlertViewDelegate
{
    [Export("alertViewCancel:")]
    public void Canceled(UIAlertView alertView)
    {
        Console.WriteLine("IUIAlertViewDelegate Cancelled");
    }

    [Export("alertView:clickedButtonAtIndex:")]
    public void Clicked(UIAlertView alertview, nint buttonIndex)
    {
        Console.WriteLine($"IUIAlertViewDelegate Clicked {buttonIndex}");
    }
}

Usage:

var autoCancelSeconds = 5;
var alert = new UIAlertView("StackOverflow", $"Auto cancel in {autoCancelSeconds} seconds", null, null, new[] { "Stack", "Over", "Flow" })
{
    Delegate = new UIAlertViewDelegate()
};
alert.Show();
await Task.Run(async () =>
{
    for (int i = autoCancelSeconds - 1; i >= 0; i--)
    {
        await Task.Delay(1000);
        InvokeOnMainThread(() =>
        {
            alert.Message = string.Format($"Auto cancel in {i} seconds");
        });
    }
    InvokeOnMainThread(() =>
    {
        alert.DismissWithClickedButtonIndex(1, true);
        alert.Delegate.Clicked(alert, 1);
    });
});

Note: UIAlertView is deprecated, you should move to using UIAlertController

SushiHangover
  • 73,120
  • 10
  • 106
  • 165
  • I'm actually already using a UIAlertController and presenting it using UIViewController.PresentViewController(AlertController). Do you know of a solution when using a UIAlertController? – Casey Hancock May 31 '17 at 16:12