Xamarin.iOS 后台 PostAsync

Xamarin.iOS PostAsync on Background

我使用 Xamarin.Forms/Xamarin.iOS 应用向 api 发送请求。但是当我将应用程序置于后台而没有 api 的回答时,PostAsync 会抛出这些错误:

System.Threading.Tasks.TaskCanceledException: A task was canceled.
  at System.Net.Http.NSUrlSessionHandler.SendAsync (System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) [0x001d4] in /Library/Frameworks/Xamarin.iOS.framework/Versions/13.20.2.2/src/Xamarin.iOS/Foundation/NSUrlSessionHandler.cs:527 
  at System.Net.Http.HttpClient.FinishSendAsyncBuffered (System.Threading.Tasks.Task`1[TResult] sendTask, System.Net.Http.HttpRequestMessage request, System.Threading.CancellationTokenSource cts, System.Boolean disposeCts) [0x0017e] in /Library/Frameworks/Xamarin.iOS.framework/Versions/Current/src/Xamarin.iOS/external/corefx/src/System.Net.Http/src/System/Net/Http/HttpClient.cs:506 

我的 PostAsync 方法是:

public async Task<LoginResponse<LoginDataResponse>> Login(LoginRequest request)
        {
            LoginResponse<LoginDataResponse> responseModel = new LoginResponse<LoginDataResponse>();
            try
            {
                string json = JsonConvert.SerializeObject(request);
                var content = new StringContent(json, Encoding.UTF8, "application/json");

                var jsonBody = await _client.PostAsync(App.ServiceURL.Login_Url, content);
                string jsonstr = await jsonBody.Content.ReadAsStringAsync();

                if (jsonstr == null || jsonstr == "")
                {
                    responseModel.Success = false;
                    responseModel.Status = 0;
                    responseModel.Message = AppResources.UnknownHostException;
                }
                else
                    responseModel = (LoginResponse<LoginDataResponse>)JsonConvert.DeserializeObject(jsonstr, typeof(LoginResponse<LoginDataResponse>));
            }
            catch (Exception ex)
            {
                string text = ex.ToString();
                responseModel.Status = 0;
                AppResources.Culture = CrossMultilingual.Current.CurrentCultureInfo;
                responseModel.Message = AppResources.UnknownHostException;
            }
            return responseModel;
        }

我的系统有一个发送通知的双因素身份验证机制。为了批准通知,我必须将我的申请置于后台。批准通知后,api 响应成功。但是,当应用程序进入后台时,我与该服务的连接中断了。如何在后台继续 PostAsync?

我找到了这个问题的解决方案。我为 iOS 添加了一个配置到 HttpClient 对象。这个配置是:

if(Device.RuntimePlatform == Device.iOS)
{
    var configuration = NSUrlSessionConfiguration.CreateBackgroundSessionConfiguration ("my.app.identifier");
    _client = new HttpClient (new NSUrlSessionHandler (configuration));
}
else
{
    //android codes
}

我将此客户端对象用于 PostAsync。对我有用。