使用async / await返回Xamarin.Forms依赖项服务回调的结果?

时间:2018-07-11 18:01:51

标签: c# xamarin.forms

我有一个Xamarin Forms项目,并实现了一个依赖服务来发送SMS,但是我不知道如何将与设备无关的回调转换为异步等待状态,以便可以将其返回。例如,在我的iOS实施中,我有类似以下内容:

[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
    }
}

我可以将public void SendSms更改为public Task<SmsResult> SendSmsAsyc,但是如何等待Finished回调并获取结果,以便我可以让SendSmsAsync返回它?

1 个答案:

答案 0 :(得分: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;
}

这样称呼:

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