0

I use HttpClient object for PostAsync. I need to add BackgroundSessionConfiguration for iOS while I am creating HttpClient object. So I changed my code like this:

var configuration = NSUrlSessionConfiguration.CreateBackgroundSessionConfiguration ("my.app.identifier");
_client = new HttpClient (new NSUrlSessionHandler (configuration));

This works when I send first request with PostAsync. But when I send request second time, it doesn't work.

I did it for Login Operation like this: (It works first time but if I logout and login again, it doesn't work.)

public class LoginService
    {
        private HttpClient _client;

        public LoginService()
        {
            if (_client == null)
                {
                    _client = Helper.CreateHttpClientLogin(_client);
                }
        }

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

public class Helper
{
    public static HttpClient CreateHttpClientLogin(HttpClient _client)
    {
            if (Device.RuntimePlatform == Device.iOS)
                {
                    var configuration = NSUrlSessionConfiguration.CreateBackgroundSessionConfiguration("my.app.identifier");
                    _client = new HttpClient(new NSUrlSessionHandler(configuration));
                }
                else
                {
                    //_client = new HttpClient(new System.Net.Http.HttpClientHandler());
                    HttpClientHandler handler = new HttpClientHandler();
                    handler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => true;
                    _client = new HttpClient(handler);
                }

            return _client;
        }
}

And I have this code on AppDelegate: (I don't know but maybe it causes the bug)

public static Action BackgroundSessionCompletionHandler;
public override void HandleEventsForBackgroundUrl(UIApplication application, string sessionIdentifier, Action completionHandler)
{
    // We get a completion handler which we are supposed to call if our transfer is done.
    BackgroundSessionCompletionHandler = completionHandler;
}

What must I do for this?

Edit:

I solved the problem I mentioned above by creating the Login Service object once the application was first opened. (After logout previously, I was rebuilding every time I login)

But now I have other error. When I run my app on "iPhone 7 plus - iOS 13.6" device I got this error:

System.Net.Http.HttpRequestException: unknown error ---> Foundation.NSErrorException: Error Domain=NSURLErrorDomain Code=-1 "unknown error" UserInfo={NSErrorFailingURLStringKey=https://mydomain/Api/Login, NSErrorFailingURLKey=https://mydomain/Api/Login, _NSURLErrorRelatedURLSessionTaskErrorKey=(
    "BackgroundDataTask <E69F3EAF-0AE9-4FAE-A01B-988167B7F6BC>.<3>"
), _NSURLErrorFailingURLSessionTaskErrorKey=BackgroundDataTask <E69F3EAF-0AE9-4FAE-A01B-988167B7F6BC>.<3>, NSLocalizedDescription=unknown error}
   --- End of inner exception stack trace ---
  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 
  at App.Services.LoginService.Login (FileOrbis.Models.RequestModels.LoginRequest request) [0x00084] in C:\Users\PcName\Desktop\App\App\Services\LoginService.cs:40

And simulator log file is:

Startup:
    arguments: --device=06098E5B-1853-4A83-8434-8071D8973A14 --launchsim=//Users/deytek/Library/Caches/Xamarin/mtbs/builds/App.iOS/b2c75f2acbd4ff91c305dba10ca791b7/bin/iPhoneSimulator/Debug/App.iOS.app -argument=-monodevelop-port -argument=51890 -setenv=__XAMARIN_DEBUG_PORT__=51890 --sdkroot=/Applications/Xcode.app -h=192.168.1.7 -ssh=deytek --launched-by=devenv-16.0 
    version: 16.7.0.0 (54a29526ef6f853bdd37adbcc3791ce90ca82735)
Connecting to existing client
Exit:
    Exit Code: 0

I encounter with this error when I use Background Session Configuration. If I use normal HttpClient object (without Background Session Configuration), it works

NOTE: I also tried iPhone 5s iOS 12.4.8 and iPad Pro (3rd Generation) iOS 13.6.1 It works these devices. But it doesn't work on iPhone 7 Plus 13.6

Pelin Konaray
  • 272
  • 1
  • 3
  • 15
  • What do you mean when you say it doesn't work? Do you get any exception or error messages? – nevermore Sep 14 '20 at 08:16
  • It doesn't return any response/error/exception. Second time I am coming this line: var jsonBody = await _client.PostAsync(App.ServiceURL.Login_Url, content); But I can't pass to below line. (So this line: string jsonstr = await jsonBody.Content.ReadAsStringAsync();) I am not getting any error or exception. – Pelin Konaray Sep 14 '20 at 08:48
  • So the app just keeps loading and the page freezes? – Saamer Sep 15 '20 at 02:11
  • Yes, app just keeps loading and the page freezes. But I put Timeout to HttpClient object and i gave an error on catch (I added this error below to my question) – Pelin Konaray Sep 15 '20 at 05:48
  • This error probably caused by a timeout and the server does not give any response. – nevermore Sep 15 '20 at 08:38
  • I solved this with create one time to LoginService object. I used to create again when I log out. But now I have other error. When I run "iPhone 7 plus - iOS 13.6" device I got this error: – Pelin Konaray Sep 15 '20 at 09:18
  • System.Net.Http.HttpRequestException: unknown error ---> Foundation.NSErrorException: Error Domain=NSURLErrorDomain Code=-1 "unknown error" UserInfo={NSErrorFailingURLStringKey=https://mydomain, NSErrorFailingURLKey=https://mydomain – Pelin Konaray Sep 15 '20 at 09:19
  • I'm so tired of dealing with this for days. I have to use BackgroundSessionConfiguration for my operation on login. But when I use it, I take this error on iphone 7 plus. – Pelin Konaray Sep 15 '20 at 09:22
  • The error is an unknow error which won't help much to solve the problem. Can you please check the device log to find more error log? – nevermore Sep 16 '20 at 07:45
  • I edited my question and I added log file. @JackHua-MSFT – Pelin Konaray Sep 23 '20 at 10:45
  • LoginService.cs:40. What is the codes there, the exception is happened from there and you should check. It still says it's a unknow error. It's quite strange if it only not work in a specific device. – nevermore Sep 24 '20 at 05:54
  • LoginService.cs:40 is this line: var jsonBody = await _client.PostAsync(App.ServiceURL.Login_Url, content); And yes it is too strange. I realized it doesn't work on plus devices. In my opinion if there is a problem with postasync or http client object, it must be related os version. But it look like related with hardware. But why. I am stuck there. – Pelin Konaray Sep 24 '20 at 06:18
  • Can you find another device with iOS 13.6(same as iphone 7 plus) and test? Then you can know if it is caused by the iOS version or the device. – nevermore Sep 24 '20 at 09:44

0 Answers0