首页 > 解决方案 > 仅适用于 iOS 真实设备的 Xamain.Forms 中 api 调用的任务取消异常

问题描述

我正在做一个应用程序,我在其中调用 web api。当我在 iPad/iPhone 中调用 api 时,我收到任务取消异常。但在模拟器和 android 设备中的响应很好。任何人都可以帮我解决这个问题。我无法确定哪里出错了。

提前致谢。

标签: xamarin.formsxamarin.ios

解决方案


尝试使用 Native Http Handler 来查看它的改进。

声明一个接口。

  public interface IHttpHandler
    {
        HttpClient ReturnHandler();
    }

Implement it this way.
public class HttpHandler : IHttpHandler
    {
        public HttpClient ReturnHandler()
        {
            try
            {
                var client = new HttpClient(new NSUrlSessionHandler()
                {
                });
                client.Timeout = TimeSpan.FromSeconds(120);
                return client;
            }
            catch (TaskCanceledException ex)
            {
                Console.WriteLine("TaskCanceledException ReturnHandler-->" + ex.Message);
                if (ex.InnerException != null)
                {
                    Console.WriteLine("TaskCanceledException ReturnHandler-->" + ex.InnerException.Message);
                }
                return null;
            }
            catch (Exception ex)
            {
                Console.WriteLine("ReturnHandler Exception-->" + ex.Message);
                if (ex.InnerException != null)
                {
                    Console.WriteLine("ReturnHandler Exception-->" + ex.InnerException.Message);
                }
                return null;
            }
        }
    }

使用 Xamarin 表单内置的依赖注入来利用我给你的接口让 HTTPClient 与本机处理程序。

如果您不知道如何阅读这里


推荐阅读