gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 22:43:10 37 4
gpt4 key购买 nike

我有一个 Xamarin Forms 项目并实现了一个依赖服务来发送短信,但我不知道如何将设备独立回调转换为异步等待,以便我可以返回它。例如,对于我的 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 SendSmspublic Task<SmsResult> SendSmsAsyc但是我如何等待 Finished 回调并得到它的结果,这样我就可以拥有 SendSmsAsync还吗?

最佳答案

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);

关于c# - 使用 async/await 返回 Xamarin.Forms 依赖服务回调的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51291736/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com