实现带有异步回调的Dependency Service

  1. Create interface and method in Forms.

    public interface IShowAlert
    {
         Task<bool> showAlert(string title, string message , string accept, string cancel);
     }
    
  2. 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;
    
             }
         }
     }
    
  3. Call the method and get the value within callback in Forms .

    bool result = await DependencyService.Get<IShowAlert>().showAlert("title","msg","ok","cancel");
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容