MtouchHttpClientHandler

MtouchHttpClientHandler

本文介绍了Xamarin iOS HttpClient超时不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尽管我们将HTTP框架的默认值设置为3分钟,但在某个时刻,我们发现应用程序中的所有请求在iOS上的超时都为60秒.我尝试了以下代码来确定是否是库出现了问题:

At some point we found all the requests in our app have timeout of 60 seconds on iOS though we set the default value for the HTTP framework we use as 3 minutes. I tried the following piece of code to figure out if it's the library who has an issue:

try
{
    using (var http = new HttpClient())
    {
        http.Timeout = TimeSpan.FromMinutes(1.5);
        await http.GetAsync("https://httpstat.us/200?sleep=70000");
    }
}
catch (Exception ex)
{
}

尽管超时设置为90秒,并且请求持续70秒,但此代码失败并带有超时异常.事实证明,它不会覆盖默认的60秒超时.相同的代码在新项目上效果很好.

This code fails with the timeout exception though the timeout is set as 90 sec and the request goes for 70 sec. Turns out it doesn't override the default timeout of 60 sec. The same code works well on the fresh project.

在项目文件中,我们有<MtouchHttpClientHandler>NSUrlSessionHandler</MtouchHttpClientHandler>

In the project file we have <MtouchHttpClientHandler>NSUrlSessionHandler</MtouchHttpClientHandler>

推荐答案

如果您不创建自己的NSUrlSessionHandler实例并提供一个自定义NSUrlSessionConfiguration在其.ctor中.

Xamarin's NSUrlSessionHandler uses the default NSUrlSessionConfiguration if you are not creating your own instance of the NSUrlSessionHandler and providing a custom NSUrlSessionConfiguration in its .ctor.

在iOS中默认的NSUrlSessionConfiguration超时设置为60秒.

The default NSUrlSessionConfiguration timeouts are set to 60 seconds in iOS.

因此,在您的Xamarin.iOS应用程序项目中,打开AppDelegate.cs并在FinishedLaunching替代项内设置默认的会话超时参数.

So in your Xamarin.iOS application project, open the AppDelegate.cs and set the default session timeout parameters within the FinishedLaunching override.

NSUrlSessionConfiguration.DefaultSessionConfiguration.TimeoutIntervalForRequest = 90.0;
NSUrlSessionConfiguration.DefaultSessionConfiguration.TimeoutIntervalForResource = 90.0;
The timeout interval to use when waiting for additional data.

timeoutIntervalForResource

timeoutIntervalForResource

The maximum amount of time that a resource request should be allowed to take.

re: https://developer .apple.com/documentation/foundation/nsurlsessionconfiguration#//apple_ref/occ/instp/NSURLSessionConfiguration/timeoutIntervalForRequest

这篇关于Xamarin iOS HttpClient超时不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 11:37