Search code examples
postxamarin.formsxamarin.iosbackgroundbackground-task

Xamarin.iOS PostAsync on Background


I send a request to api with Xamarin.Forms/Xamarin.iOS app. But When I put the application in the background without an answer from api, PostAsync throws these error:

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 

My PostAsync method is:

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;
        }

My system has a two factor authentication mechanizm which sends notification. In order to approve notification, I have to put my application on background. After approving the notification, api responses with a successful result. However, my connection to the service brokes down when the application goes background. How can I continue PostAsync on background?


Solution

  • I found a solution for this problem. I added a configuration to HttpClient object for iOS. This configuration is:

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

    And I use this client object for PostAsync. It works for me.