实现带有异步回调的Dependency Service
2018-10-05 本文已影响26人
ColeX
-
Create interface and method in Forms.
public interface IShowAlert { Task<bool> showAlert(string title, string message , string accept, string cancel); }
-
Inherit from the interface and implement the method in iOS project
[assembly: Dependency(typeof(ShowAlert))] namespace PPPPCL.iOS { class ShowAlert : IShowAlert { public async Task<bool> showAlert(string title, string message ,string accept, string cancel) { var tcs = new TaskCompletionSource<bool>(); UIAlertController vc = UIAlertController.Create(title,message, UIAlertControllerStyle.Alert); UIAlertAction action = UIAlertAction.Create(accept, UIAlertActionStyle.Default, (e) =>{ tcs.SetResult(true);}); vc.AddAction(action); UIAlertAction action2 = UIAlertAction.Create(cancel, UIAlertActionStyle.Destructive, (e) => { tcs.SetResult(false);}); vc.AddAction(action2); (UIApplication.SharedApplication.Delegate as AppDelegate).Window.RootViewController.PresentViewController(vc, true, null); return await tcs.Task; } } }
-
Call the method and get the value within callback in Forms .
bool result = await DependencyService.Get<IShowAlert>().showAlert("title","msg","ok","cancel");