发起电话呼叫,然后返回到应用 - Xamarin
本文关键字:应用 Xamarin 返回 然后 电话 呼叫 | 更新日期: 2023-09-27 18:33:57
在我的 Xamarin 应用程序中,用户单击某个按钮后,我想拨打电话,然后返回到我的应用(理想情况下是代码中的同一位置)。
像这样:
async Task button_click()
{
string s = "200-345-6789";
// await Device.OpenUri("tel:" + s); // can't await this
ShowAlert("The number " + s + " was called");
}
最初我尝试了Device.OpenUri,但它无法等待。
在Android上,StartActivityWithResult对我来说效果很好。我定义了 TaskCompletionSource,以 ActionCall 为目的启动活动,在 OnActivityResult 函数中,我将我的任务标记为已完成,这会将流返回到原始函数。
但是在iOS上,我找不到类似的东西。你有什么建议?
注意:这是一个常见的 Xamarin iOS 异步 uri 模式,不要将其声明为我自己的模式,因为它在许多 OSS 库中使用:
public Task<bool> LaunchUriAsync(Uri uri)
{
var completion = new TaskCompletionSource<bool>();
var sharedApp = UIApplication.SharedApplication;
sharedApp.BeginInvokeOnMainThread(() =>
{
try
{
var url = NSUrl.FromString(uri.ToString()) ?? new NSUrl(uri.Scheme, uri.Host, uri.LocalPath);
var result = sharedApp.CanOpenUrl(url) && sharedApp.OpenUrl(url);
completion.SetResult(result);
}
catch (Exception exception)
{
completion.SetException(exception);
}
});
return completion.Task;
}
例子:
await LaunchUriAsync(new Uri("mailto:demo@example.com"));
await LaunchUriAsync(new Uri("tel:555-555-5555"));
await LaunchUriAsync(new Uri("https://www.google.com"));
await LaunchUriAsync(new Uri("sms:555-555-5555"));
在弄乱了几个小时之后,我找到了解决方案 - 所以我想我会发布它让其他人受益。我所做的是模拟类似于Android OnActivityResult
的东西。在我的AppDelegate
类中,我定义了一个从其OnActivated
函数触发的事件。现在,在我的函数中,我订阅了这个事件,将我定义的TaskCompletionSource
传递给委托。然后我打电话给Device.OpenUri("tel:" + phoneNum)
.电话呼叫完成后,用户返回到我的应用,AppDelegate.OnActivated
触发我的事件,调用我的代理,我可以通过调用 SetResult
将我的任务标记为已完成。这使得await
此功能成为可能。
telprompt:<phone-number>
方案,这将在调用完成后将用户返回到您的应用。
只有一句话,这个方案没有得到苹果的正式支持,所以他们可能会删除它。
在iOS上拨打号码只有两种方法,tel:<phone-number>
或telprompt:<phone-number>
。没有其他方法。