I have to show an UI alert dialog in the Appdelegate and MainAcvitivy in Xamarin.Forms. For android, there is no problem but for ios it does not work properly.
First of all, if I use UIAlertView, it works without problem.
Task.Run(async () =>
{
await Device.InvokeOnMainThreadAsync(() =>
{
var alertView = new UIAlertView("Title", $"Message", null, "OK") { UserInteractionEnabled = true };
alertView.Clicked += (sender, args) =>
{
File.Delete(errorFilePath);
};
alertView.Show();
}).ConfigureAwait(false);
}).ConfigureAwait(false);
but unfortunately UIAlertView is deprecated. That's why I use UIViewController.
Nevertheless I can see the alert around 0.5 second in the splash screen but after that, I show my main page and the alert is gone.
Here is the code
Task.Run(async () =>
{
await Device.InvokeOnMainThreadAsync(() =>
{
UIAlertController alertView = UIAlertController.Create("Title", $"Message", UIAlertControllerStyle.Alert);
alertView.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, (action) => File.Delete(errorFilePath)));
TopViewController.PresentViewController(alertView, true, null);
//var appDelegate = (AppDelegate)UIApplication.SharedApplication.Delegate;
//appDelegate.Window.RootViewController.PresentViewController(alertView, true, null);
}).ConfigureAwait(false);
}).ConfigureAwait(false);
and here is my TopViewContoller
public static UIViewController TopViewController
{
get
{
UIApplication.SharedApplication.KeyWindow.WindowLevel = UIWindowLevel.Alert +1;
UIApplication.SharedApplication.KeyWindow.BackgroundColor = UIColor.Clear;
UIApplication.SharedApplication.KeyWindow.UpdateConstraints();
UIApplication.SharedApplication.KeyWindow.MakeKeyAndVisible();
UIApplication.SharedApplication.KeyWindow.RootViewController.UpdateViewConstraints();
return TopViewControllerWithRootViewController(UIApplication.SharedApplication.KeyWindow.RootViewController);
}
}
What does the code look like in method
TopViewControllerWithRootViewController
?Could you just replace
TopViewController
withUIApplication.SharedApplication.KeyWindow.RootViewController
and try again ?And why you place the code into a Task , it is unnecessary .
Remove the outer Task and just try the following code ,it works fine on my side .