简体   繁体   中英

Xamarin.Forms iOS throwing NSURLErrorDomain "internet connection offline" when device is online

When calling a request from the HTTP manager the application throws an NSURL Error that states the internet connection is offline.

Foundation.NSErrorException: Error Domain=NSURLErrorDomain Code=-1009 "The Internet connection appears to be offline."

This is only happening sometimes and every time that it is happening the device has internet access.

Upon attempting to debug the solution it seems that the rest service call for client.GetAsync isn't returning a response.

public async Task<T> callGetAsync<T>(string path) {
    using(var client = new HttpClient()) {
        var result = default(T);

        client.BaseAddress = new Uri(url);
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        if (App.User.Context != null)
        {
            client.DefaultRequestHeaders.Authorization =
            new AuthenticationHeaderValue("Bearer", App.User.Context.AccessToken);
        }

        HttpResponseMessage response = await client.GetAsync(path);
        if(response.IsSuccessStatusCode) {
            string json = await response.Content.ReadAsStringAsync();
            result = JsonConvert.DeserializeObject<T>(json);
        }
        else {
            Console.WriteLine("Error");
            Analytics.TrackEvent($"API Failure: {path}");
        }
        return result;
    }
}

The expected result is the application should successfully make the call and return the desired results, instead the application is suggesting the internet connection is offline.

Has anyone else seen this behavior? If so, have you been able to solve it?

This has been reported to be an issue with Visual Studio Preview builds. Downgrading back to the latest stable release has fixed the issue for now.

https://github.com/xamarin/xamarin-macios/issues/6762#issuecomment-524016733

I found this and Visual Studio 2019 is long out of preview. Looking up this error in different places. I read "Check the URL that you are using and make sure that is correct" and thought of course it is. I was wrong. So this is a friendly reminder. Check your pride and the URL :) Don't worry I made the same mistake.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM