Using async/await to return the result of a Xamarin.Forms dependency service callback?

我与影子孤独终老i 提交于 2021-02-08 06:38:34

问题


I have a Xamarin Forms project and implemented a dependency service to send an SMS but I can't figure out how to convert the device independent callbacks into an async await so that I can return it. For example, with my iOS implementation I have something like:

[assembly: Xamarin.Forms.Dependency(typeof(MySms))]
namespace MyProject.iOS.DS
{
    class MySms : IMySms
    {
        // ...

       public void SendSms(string to = null, string message = null)
        {
            if (MFMessageComposeViewController.CanSendText)
            {
                MFMessageComposeViewController smsController= new MFMessageComposeViewController();
                // ...
                smsController.Finished += SmsController_Finished;
            }
        }
    }
    private void SmsController_Finished(object sender, MFMessageComposeResultEventArgs e)
    {
        // Convert e.Result into my smsResult enumeration type
    }
}

I can change public void SendSms to public Task<SmsResult> SendSmsAsyc but how do I await for the Finished callback and get it's result so that I can have SendSmsAsync return it?


回答1:


public interface IMySms
{
    Task<bool> SendSms(string to = null, string message = null);
}

public Task<bool> SendSms(string to = null, string message = null)
{
    //Create an instance of TaskCompletionSource, which returns the true/false
    var tcs = new TaskCompletionSource<bool>();

    if (MFMessageComposeViewController.CanSendText)
    {
        MFMessageComposeViewController smsController = new MFMessageComposeViewController();

        // ...Your Code...             

        //This event will set the result = true if sms is Sent based on the value received into e.Result enumeration
        smsController.Finished += (sender, e) =>
        {
             bool result = e.Result == MessageComposeResult.Sent;
             //Set this result into the TaskCompletionSource (tcs) we created above
             tcs.SetResult(result);
        };
    }
    else
    {
        //Device does not support SMS sending so set result = false
        tcs.SetResult(false);
    }
    return tcs.Task;
}

Call it like:

bool smsResult = await DependencyService.Get<IMySms>().SendSms(to: toSmsNumber, message: smsMessage);


来源:https://stackoverflow.com/questions/51291736/using-async-await-to-return-the-result-of-a-xamarin-forms-dependency-service-cal

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!