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?
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.