使用 async/await 返回 Xamarin.Forms 依赖服务回调的结果? [英] Using async/await to return the result of a Xamarin.Forms dependency service callback?
本文介绍了使用 async/await 返回 Xamarin.Forms 依赖服务回调的结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个 Xamarin Forms 项目并实现了一个依赖服务来发送 SMS,但我不知道如何将设备无关的回调转换为异步等待,以便我可以返回它.例如,对于我的 iOS 实现,我有类似的东西:
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
}
}
我可以将 public void SendSms
更改为 public Task
但是我如何等待 Finished 回调并获得它的结果,以便我可以让 SendSmsAsync
返回它?
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?
推荐答案
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);
这篇关于使用 async/await 返回 Xamarin.Forms 依赖服务回调的结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文