Nsurlerrordomain ошибка 1005

I have this issue also, running on an iOS 8 device.
It is detailed some more here and seems to be a case of iOS trying to use connections that have already timed out.
My issue isn’t the same as the Keep-Alive problem explained in that link, however it seems to be the same end result.

I have corrected my problem by running a recursive block whenever I receive an error -1005 and this makes the connection eventually get through even though sometimes the recursion can loop for 100+ times before the connection works, however it only adds a mere second onto run times and I bet that is just the time it takes the debugger to print the NSLog’s for me.

Here’s how I run a recursive block with AFNetworking:
Add this code to your connection class file

// From Mike Ash's recursive block fixed-point-combinator strategy https://gist.github.com/1254684
dispatch_block_t recursiveBlockVehicle(void (^block)(dispatch_block_t recurse))
{
    // assuming ARC, so no explicit copy
    return ^{ block(recursiveBlockVehicle(block)); };
}
typedef void (^OneParameterBlock)(id parameter);
OneParameterBlock recursiveOneParameterBlockVehicle(void (^block)(OneParameterBlock recurse, id parameter))
{
    return ^(id parameter){ block(recursiveOneParameterBlockVehicle(block), parameter); };
}

Then use it likes this:

+ (void)runOperationWithURLPath:(NSString *)urlPath
            andStringDataToSend:(NSString *)stringData
                    withTimeOut:(NSString *)timeOut
     completionBlockWithSuccess:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
                        failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
{
    OneParameterBlock run = recursiveOneParameterBlockVehicle(^(OneParameterBlock recurse, id parameter) {
        // Put the request operation here that you want to keep trying
        NSNumber *offset = parameter;
        NSLog(@"--------------- Attempt number: %@ ---------------", offset);

        MyAFHTTPRequestOperation *operation =
            [[MyAFHTTPRequestOperation alloc] initWithURLPath:urlPath
            andStringDataToSend:stringData
            withTimeOut:timeOut];

        [operation setCompletionBlockWithSuccess:
            ^(AFHTTPRequestOperation *operation, id responseObject) {
                success(operation, responseObject);
            }
            failure:^(AFHTTPRequestOperation *operation2, NSError *error) {
                if (error.code == -1005) {
                    if (offset.intValue >= numberOfRetryAttempts) {
                        // Tried too many times, so fail
                        NSLog(@"Error during connection: %@",error.description);
                        failure(operation2, error);
                    } else {
                        // Failed because of an iOS bug using timed out connections, so try again
                        recurse(@(offset.intValue+1));
                    }
                } else {
                    NSLog(@"Error during connection: %@",error.description);
                    failure(operation2, error);
                }
            }];
        [[NSOperationQueue mainQueue] addOperation:operation];
    });
    run(@0);
}

You’ll see that I use a AFHTTPRequestOperation subclass but add your own request code. The important part is calling recurse(@offset.intValue+1)); to make the block be called again.

У меня есть приложение, которое отлично работает на Xcode6-Beta1 и Xcode6-Beta2 с iOS7 и iOS8. Но с Xcode6-Beta3, Beta4, Beta5 я столкнулся с проблемами сети с iOS8, но все отлично работает на iOS7. Я получаю сообщение об ошибке "The network connection was lost.". Ошибка следующая:

Ошибка: Ошибка домена = NSURLErrorDomain Code = -1005 «Сетевое соединение было потеряно». UserInfo = 0x7ba8e5b0 {NSErrorFailingURLStringKey =, _kCFStreamErrorCodeKey = 57, NSErrorFailingURLKey =, NSLocalizedDescription = Сетевое соединение было потеряно., _kCFStreamErrorDomainKey = 1, NSUnderlyingError = 0x7a6957e0 «Сетевое соединение было потеряно.» }

Я использую AFNetworking 2.x и следующий фрагмент кода для выполнения сетевого вызова:

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager setSecurityPolicy:policy];
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];

[manager POST:<example-url>
   parameters:<parameteres>
      success:^(AFHTTPRequestOperation *operation, id responseObject) {
          NSLog(@"Success: %@", responseObject);
      } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
          NSLog(@"Error: %@", error);
      }];

Я пробовал NSURLSession, но все равно получаю ту же ошибку.

4b9b3361

Ответ 1

Перезапуск симулятора исправил проблему для меня.

Ответ 2

У нас была именно эта ошибка, и она оказалась проблемой с базовой реализацией HTTP NSURLRequest:

Насколько мы можем судить, когда iOS 8/9/10/11 получает HTTP-ответ с заголовком Keep-Alive, она сохраняет это соединение для повторного использования позже (как и должно быть), но сохраняет его больше, чем Параметр timeout заголовка Keep-Alive (кажется, он всегда поддерживает соединение в течение 30 секунд.) Затем, когда приложение отправляет второй запрос менее чем через 30 секунд, оно пытается повторно использовать соединение, которое могло быть сбрасывается сервером (если прошло больше, чем реальный Keep-Alive).

Вот решения, которые мы нашли до сих пор:

  • Увеличьте параметр времени ожидания сервера выше 30 секунд. Похоже, что iOS всегда ведет себя так, как будто сервер будет держать соединение открытым в течение 30 секунд, независимо от значения, указанного в заголовке Keep-Alive. (Это можно сделать для Apache, установив параметр KeepAliveTimeout.
  • Вы можете просто отключить механизм поддержания активности для клиентов iOS на основе User-Agent вашего приложения (например, для Apache: BrowserMatch "iOS 8." nokeepalive в файле мода setenvif.conf)
  • Если у вас нет доступа к серверу, вы можете попробовать отправить ваши запросы с заголовком Connection: close: это скажет серверу немедленно прекратить соединение и ответить без заголовков поддержки активности. НО в настоящий момент NSURLSession, кажется, переопределяет заголовок Connection при отправке запросов (мы не тестировали это решение всесторонне, так как мы можем настроить конфигурацию Apache)

Ответ 3

Для моего, Resetting content and settings симулятора работает.
В reset симулятор выполнит следующие шаги:

iOS Simulator → reset Содержание и настройки → Нажмите reset (на предупреждение, которое придет)

Ответ 4

Время выполнения симулятора iOS 8.0 имеет ошибку, согласно которой, если ваша сетевая конфигурация изменяется при загрузке имитируемого устройства, API-интерфейсы более высокого уровня (например, CFNetwork) в моделируемой среде выполнения будут считать, что он потерял сетевое подключение. В настоящее время рекомендуемым решением является просто перезагрузка имитируемого устройства при изменении конфигурации сети.

Если вы столкнулись с этой проблемой, добавьте дополнительные дублированные радары в http://bugreport.apple.com, чтобы получить повышенный приоритет.

Если вы видите эту проблему, не изменив конфигурации сети, то это не известная ошибка, и вы обязательно должны указать радар, указав, что проблема не является известной ошибкой, измененной конфигурацией сети.

Ответ 5

Также есть проблема с бета 5 и AFNetworking 1.3 при работе на симуляторе iOS 8, которая приводит к ошибке соединения:

Domain = NSURLErrorDomain Code = -1005 «Сетевое соединение потеряно.»

Тот же самый код прекрасно работает на симуляторах iOS 7 и 7.1, и мой прокси-сервер отладки показывает, что сбой происходит до того, как на самом деле попытка подключения (т.е. Запросы не регистрируются).

Я отследил сбой NSURLConnection и сообщил об ошибке в Apple. Смотрите строку 5 на прикрепленном изображении:

NSURLConnection client delegate did fail error.

Изменение использования https позволяет подключаться к симуляторам iOS 8, хотя и с периодическими ошибками.

Проблема все еще присутствует в Xcode 6.01 (gm).

Ответ 6

для меня проблема заключалась в том, чтобы перезапустить симулятор и reset содержимое и настройки.

Ответ 7

Открытие Чарльза решило проблему для меня, что кажется очень странным…

Charles — это прокси-сервер HTTP/HTTP-монитор/обратный прокси-сервер, который позволяет разработчику просматривать весь трафик HTTP и SSL/HTTPS между их компьютером и Интернетом. Это включает в себя запросы, ответы и заголовки HTTP (которые содержат файлы cookie и информацию о кэшировании).

Ответ 8

Я столкнулся с этой проблемой при использовании Alamofire. Моя ошибка заключалась в том, что я отправлял пустой словарь [:] для параметров по запросу GET, а не по отправке параметров nil.

Надеюсь, это поможет!

Ответ 9

См. комментарий pjebs от 5 января в Github.

Метод1:

if (error.code == -1005)
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{

        dispatch_group_t downloadGroup = dispatch_group_create();
        dispatch_group_enter(downloadGroup);
        dispatch_group_wait(downloadGroup, dispatch_time(DISPATCH_TIME_NOW, 5000000000)); // Wait 5 seconds before trying again.
        dispatch_group_leave(downloadGroup);
        dispatch_async(dispatch_get_main_queue(), ^{
            //Main Queue stuff here
            [self redoRequest]; //Redo the function that made the Request.
        });
    });

    return;
}

Также некоторые предлагают повторно подключиться к сайту,

то есть. Сбой запроса POST TWICE

Решение. Используйте метод для подключения к сайту, return (id), если сетевое соединение было потеряно, верните его, чтобы использовать тот же метод.

Метод 2

-(id) connectionSitePost:(NSString *) postSender Url:(NSString *) URL {
     // here set NSMutableURLRequest =>  Request

    NSHTTPURLResponse *UrlResponse = nil;
    NSData *ResponseData = [[NSData alloc] init];

    ResponseData = [NSURLConnection sendSynchronousRequest:Request returningResponse:&UrlResponse error:&ErrorReturn];

     if ([UrlResponse statusCode] != 200) {

          if ([UrlResponse statusCode] == 0) {

                  /**** here re-use method ****/
                  return [self connectionSitePost: postSender Url: URL];
          }

     } else {
          return ResponseData;
     }

}

Ответ 10

Я тоже получал эту ошибку, но на реальных устройствах, а не на симуляторе. Мы заметили ошибку при доступе к нашему серверу heroku на HTTPS (сервер gunicorn) и сделали POSTS с большими bodys (что-то более 64Kb). Мы используем HTTP Basic Auth для аутентификации и заметили, что ошибка была решена НЕ используя метод делегата didReceiveChallenge: на NSURLSession, а скорее выпекаем в аутентификации в исходный заголовок запроса, добавив Authentiation: Basic <Base64Encoded UserName:Password>. Это предотвращает необходимость 401 для запуска сообщения делегата didReceiveChallenge:, а последующее сетевое соединение потеряно.

Ответ 11

У меня была такая же проблема. Решение было простым, я установил HTTPBody, но не установил HTTPMethod в POST. После исправления все было в порядке.

Ответ 12

У меня такая же проблема. Я не знаю, как AFNetworking реализует запрос https, но причина для меня — проблема с кешем NSURLSession.

После отслеживания моего приложения из safari и последующей отправки запроса http появится сообщение «Ошибка загрузки http 1005». Если я перестану использовать "[NSURLSession sharedSession]", но использовать настраиваемый экземпляр NSURLSession для вызова метода «dataTaskWithRequest:» следующим образом, проблема будет решена.

NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
config.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
config.URLCache = nil;
self.session = [NSURLSession sessionWithConfiguration:config];

Просто не забудьте установить config.URLCache = nil; ,

Ответ 13

Мне пришлось выйти из XCode, удалить содержимое папки DerivedData (~/Library/Developer/Xcode/DerivedData или /Library/Developer/Xcode/DerivedData ) и выйти из симулятора, чтобы сделать эту работу.

Ответ 14

У меня тоже есть эта проблема, работающая на устройстве iOS 8.
Здесь подробно описано и, похоже, это случай, когда iOS пытается использовать соединения, которые уже были отключены.
Моя проблема не совпадает с проблемой Keep-Alive, описанной в этой ссылке, однако, похоже, это тот же конечный результат.

Я исправил свою проблему, запустив рекурсивный блок всякий раз, когда получаю сообщение об ошибке -1005, и это приводит к тому, что соединение в конечном итоге проходит, хотя иногда рекурсия может зацикливаться на 100 раз, прежде чем соединение будет работать, однако оно добавляет просто второй — во время выполнения, и я уверен, что это всего лишь время, когда отладчик должен распечатать NSLog для меня.

Вот как я запускаю рекурсивный блок с AFNetworking:
Добавьте этот код в файл класса подключения

// From Mike Ash recursive block fixed-point-combinator strategy https://gist.github.com/1254684
dispatch_block_t recursiveBlockVehicle(void (^block)(dispatch_block_t recurse))
{
    // assuming ARC, so no explicit copy
    return ^{ block(recursiveBlockVehicle(block)); };
}
typedef void (^OneParameterBlock)(id parameter);
OneParameterBlock recursiveOneParameterBlockVehicle(void (^block)(OneParameterBlock recurse, id parameter))
{
    return ^(id parameter){ block(recursiveOneParameterBlockVehicle(block), parameter); };
}

Затем использовать его нравится это:

+ (void)runOperationWithURLPath:(NSString *)urlPath
            andStringDataToSend:(NSString *)stringData
                    withTimeOut:(NSString *)timeOut
     completionBlockWithSuccess:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
                        failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
{
    OneParameterBlock run = recursiveOneParameterBlockVehicle(^(OneParameterBlock recurse, id parameter) {
        // Put the request operation here that you want to keep trying
        NSNumber *offset = parameter;
        NSLog(@"--------------- Attempt number: %@ ---------------", offset);

        MyAFHTTPRequestOperation *operation =
            [[MyAFHTTPRequestOperation alloc] initWithURLPath:urlPath
            andStringDataToSend:stringData
            withTimeOut:timeOut];

        [operation setCompletionBlockWithSuccess:
            ^(AFHTTPRequestOperation *operation, id responseObject) {
                success(operation, responseObject);
            }
            failure:^(AFHTTPRequestOperation *operation2, NSError *error) {
                if (error.code == -1005) {
                    if (offset.intValue >= numberOfRetryAttempts) {
                        // Tried too many times, so fail
                        NSLog(@"Error during connection: %@",error.description);
                        failure(operation2, error);
                    } else {
                        // Failed because of an iOS bug using timed out connections, so try again
                        recurse(@(offset.intValue+1));
                    }
                } else {
                    NSLog(@"Error during connection: %@",error.description);
                    failure(operation2, error);
                }
            }];
        [[NSOperationQueue mainQueue] addOperation:operation];
    });
    run(@0);
}

Вы увидите, что я использую подкласс AFHTTPRequestOperation, но добавляю свой собственный код запроса. Важной частью является вызов recurse(@offset.intValue+1)); для повторного вызова блока.

Ответ 15

Я получал ошибку на устройстве iOS 7, когда я использовал бета-версию Xcode 6.2.

Переход с бета-версии Xcode 6.2 на 6.1.1 исправил проблему, по крайней мере, на устройстве iOS 7.

Ответ 16

Если проблема возникает на устройстве, проверьте, проходит ли трафик через прокси (Настройки > Wi-Fi > (информация) > HTTP-прокси). У меня была настройка устройства для использования с Чарльзом, но я забыл про прокси. Кажется, что без того, чтобы Чарльз действительно выполнял эту ошибку.

Ответ 17

Если кто-то получает эту ошибку при загрузке файлов на серверный сервер, убедитесь, что на принимающем сервере установлен максимальный размер содержимого, допустимый для вашего носителя. В моем случае для NGINX требуется более высокий client_max_body_size. NGINX отклонил запрос до того, как будет выполнена загрузка, поэтому код ошибки не вернулся.

Ответ 18

На 2017-01-25 Apple выпустила технический Q & A относительно этой ошибки:

Технические вопросы и ответы Apple QA1941

Обработка ошибок «сетевое соединение потеряно»

A: NSURLErrorNetworkConnectionLost является ошибкой -1005 в домене ошибок NSURLErrorDomain и отображается для пользователей как «Сетевое соединение было потеряно». Эта ошибка означает, что базовое TCP-соединение, несущее HTTP-запрос, отключено во время выполнения HTTP-запроса (дополнительную информацию об этом см. Ниже). В некоторых случаях NSURLSession может повторять такие запросы автоматически (в частности, если запрос идемпотентен), но в других случаях, которые не допускаются стандартами HTTP.

https://developer.apple.com/library/archive/qa/qa1941/_index.html#//apple_ref/doc/uid/DTS40017602

Ответ 19

Получил проблему в течение нескольких месяцев и, наконец, обнаружил, что когда мы отключили DNSSEC в нашем домене api, все было в порядке:

Ответ 20

Я подключался через VPN. Отключение VPN решило проблему.

Ответ 21

Я ударил эту ошибку при передаче NSURLRequest в NSURLSession без установки запроса HTTPMethod.

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:urlComponents.URL];

Ошибка домена = NSURLErrorDomain Code = -1005 «Сетевое соединение было потеряно».

Добавьте HTTPMethod, хотя соединение прекрасно работает

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:urlComponents.URL];
[request setHTTPMethod:@"PUT"];

Ответ 22

Проверьте, можете ли вы запросить другие приложения (например, сафари). Если это не может быть что-то на вашем компьютере. В моем случае у меня была эта проблема с Avast Antivirus, которая блокировала мой запрос симуляторов (не спрашивайте меня почему).

Ответ 23

Перезапуск компьютера исправил проблему для меня с помощью Xcode9.1. Я перезапустил симулятор и Xcode, он не работает.

Ответ 24

У меня была эта проблема по следующей причине.

TL;DR: Проверьте, отправляется ли запрос GET, который должен отправлять параметры на URL, а не в свойстве NSURLRequest HTTBody.

=============================================== ===

Я установил сетевую абстракцию в своем приложении, и он работал очень хорошо для всех моих запросов.

Я добавил новый запрос на другой веб-сервис (не мой), и он начал бросать мне эту ошибку.

Я пошел на детскую площадку и начал с нуля строить строгий запрос, и это сработало. Поэтому я начал приближаться к своей абстракции, пока не нашел причину.

У моей реализации абстракции была ошибка:
Я отправил запрос, который должен был отправить параметры, закодированные в URL-адресе, и я также заполнил свойство NSURLRequest HTTBody параметрами запроса.
Как только я удалил HTTPBody, он сработал.

Ответ 25

Я получал эту ошибку и также замечаю, что приложение Postman также падало, но работало в приложении Advanced Rest Client (ARC) и работало в Android.
Поэтому мне пришлось установить Charles для отладки сообщения, и я замечаю, что код ответа был -1.
Проблема заключалась в том, что программист REST забыл вернуть код ответа 200.

Я надеюсь, что это поможет другим разработчикам.

Ответ 26

Всякий раз, когда появляется ошибка -1005, необходимо снова вызвать API.

AFHTTPRequestOperationManager *manager = 
[AFHTTPRequestOperationManager manager];
[manager setSecurityPolicy:policy];
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];

[manager POST:<example-url>
   parameters:<parameteres>
    success:^(AFHTTPRequestOperation *operation, id responseObject) {
      NSLog(@"Success: %@", responseObject);
  } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
      NSLog(@"Error: %@", error);
      if (error.code == -1005) {
          // Call method again... 
       }
  }];

Вам нужно добавить свой код, чтобы снова вызвать функцию. Убедитесь, что вы вызывали метод один раз, иначе вызовите рекурсивный цикл.

Ответ 27

Я столкнулся с той же проблемой, я включил Network Link Conditioner для медленного тестирования сети для приложения. Это создавало эту ошибку несколько раз. Когда я отключил ее в Settings > Developer > Network Link Conditioner, это решило мою проблему.

enter image description here

Надеюсь, это поможет кому-то.

Ответ 28

Я столкнулся с той же проблемой, когда звонил, используя сервер своей компании из приложения iOS 12 с физического устройства. Проблема заключалась в том, что жесткий диск сервера был заполнен. Освобождение места на сервере решило проблему.

Я обнаружил ту же ошибку в другой ситуации, которую я считаю из-за тайм-аута, который нельзя параметризировать через стандартный сетевой API, предоставляемый Apple (URLSession.timeoutIntervalForRequest и URLSession.timeoutIntervalForResource). Даже там.. сделал ответ сервера быстрее решил проблему

Ответ 29

В моем случае это было связано с тем, что я подключался к HTTP, и он работал по протоколу HTTPS.

Ответ 30

Это может быть проблемой параметра, который вы передаете в тело запроса. Я также столкнулся с той же проблемой. Но потом я наткнулся на ответ CMash здесь fooobar.com/info/127920/…, и я изменил свой параметр, и он работает.

Проблема в параметре, который я передавал, касается String Encoding.

Надеюсь это поможет.

When i’m calling service, it will give below error response.

I did google and restarted Xcode and simulator. its not working for me. even in device also i’m facing same issue. can any one help me.

Service calling:

    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@?%@", urlString,paramsString]];
    theRequest = [[NSMutableURLRequest alloc] initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:120.0];

    if (paramsString!=nil)
    {
        NSString *msgLength = [[NSString alloc]initWithFormat:@"%lu",(unsigned long)[paramsString length]];
        [theRequest addValue:msgLength forHTTPHeaderField:@"Content-Length"];
    }
    [theRequest setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [theRequest setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];

    [theRequest setValue:[NSString stringWithFormat:@"authToken=%@",self.authToken] forHTTPHeaderField:@"Cookie"];

    theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];

    if (theConnection)
    {
        self.receivedData=[[NSMutableData alloc] init];
    }

Error:

Error Domain=NSURLErrorDomain Code=-1005 "The network connection was lost." UserInfo=0x7c3770a0 {NSErrorFailingURLStringKey=serviceUrl, _kCFStreamErrorCodeKey=-4, NSErrorFailingURLKey=serviceUrl, NSLocalizedDescription=The network connection was lost., _kCFStreamErrorDomainKey=4, NSUnderlyingError=0x79769170 "The network connection was lost."}

Steps to Reproduce

  1. Start any HTTPS GET or POST request with physical iPhone 5S (12.4.4) or iPad (13.3) device.
    The iOS Simulator works fine, and the Xamarin.Android (Simulator and physical device) project is also works fine. Only occured in iOS physical devices.

My HttpClient code in Xamarin.iOS project:

private bool NSUrlSessionHandlerTrustOverride(NSUrlSessionHandler sender, SecTrust trust)
{
    return true;
}

public HttpClient PrepareHttpClient(HttpMessageHandler handler)
{
    return new HttpClient(
        new NSUrlSessionHandler(NSUrlSessionConfiguration.DefaultSessionConfiguration)
        {
            TrustOverride = this.NSUrlSessionHandlerTrustOverride,
            AllowsCellularAccess = true
        });
}

Expected Behavior

The connection is established.

Actual Behavior

Exception Type: System.Net.Http.HttpRequestException (Code: HResult: -2146233088)
Exception Message: The network connection was lost.
  at System.Net.Http.NSUrlSessionHandler.SendAsync (System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) [0x001d4] in /Library/Frameworks/Xamarin.iOS.framework/Versions/13.16.0.13/src/Xamarin.iOS/Foundation/NSUrlSessionHandler.cs:462 
  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 MLR.MoLaRi.UI.WebVUK.Mobile.MM.WebVUKApi.CApiCallHelper.PostRequest[T] (MLR.Components.FuncLog.CFL fL, System.String method, MLR.MoLaRi.UI.WebVUK.Shared.Api.IMethodParameters parameters) [0x000bb] in <2f969a191e1d477da78f5fcaf446e542>:0 
InnerException Type: Foundation.NSErrorException (Code: HResult: -2146233088)

InnerException Message: Error Domain=NSURLErrorDomain Code=-1005 "The network connection was lost." UserInfo={_kCFStreamErrorCodeKey=54, NSUnderlyingError=0x283273b10 {Error Domain=kCFErrorDomainCFNetwork Code=-1005 "(null)" UserInfo={_kCFStreamErrorCodeKey=54, _kCFStreamErrorDomainKey=1}}, _NSURLErrorFailingURLSessionTaskErrorKey=LocalDataTask <3EC77204-455C-48B5-BFAB-6E2CB187DC47>.<1>, _NSURLErrorRelatedURLSessionTaskErrorKey=(
    "LocalDataTask <3EC77204-455C-48B5-BFAB-6E2CB187DC47>.<1>"
), NSLocalizedDescription=The network connection was lost., NSErrorFailingURLStringKey=https://10.42.42.8:444/Home/MobileLogin, NSErrorFailingURLKey=https://10.42.42.8:444/Home/MobileLogin, _kCFStreamErrorDomainKey=1}

On the server side with wireshark only find these five rows for this connection.
wireshark1

The server immediately response with reset -> this is the reason with the 1005 error code.
wireshark1

In the server no IIS log in %SystemDrive%inetpublogsLogFiles, but when I test it with simulator or Android device the IIS logs are written fine.

Environment

Microsoft Visual Studio Professional 2019
Version 16.5.4
VisualStudio.16.Release/16.5.4+30011.22
Microsoft .NET Framework
Version 4.8.03752

Installed Version: Professional

Visual C++ 2019   00435-60000-00000-AA607
Microsoft Visual C++ 2019

.NET Portability Analyzer   1.1.10808.0
Evaluates portability of assemblies across .NET platforms.

ASP.NET and Web Tools 2019   16.5.236.49856
ASP.NET and Web Tools 2019

ASP.NET Web Frameworks and Tools 2019   16.5.236.49856
For additional information, visit https://www.asp.net/

Azure App Service Tools v3.0.0   16.5.236.49856
Azure App Service Tools v3.0.0

Azure Functions and Web Jobs Tools   16.5.236.49856
Azure Functions and Web Jobs Tools

C# Tools   3.5.0-beta4-20153-05+20b9af913f1b8ce0a62f72bea9e75e4aa3cf6b0e
C# components used in the IDE. Depending on your project type and settings, a different version of the compiler may be used.

Common Azure Tools   1.10
Provides common services for use by Azure Mobile Services and Microsoft Azure Tools.

Extensibility Message Bus   1.2.0 (d16-2@8b56e20)
Provides common messaging-based MEF services for loosely coupled Visual Studio extension components communication and integration.

GitHub.VisualStudio   2.11.96.24460
A Visual Studio Extension that brings the GitHub Flow into Visual Studio.

IntelliCode Extension   1.0
IntelliCode Visual Studio Extension Detailed Info

Language   1.0
Generate language cs file

License Header Manager   3.0.3
An extension for automatically inserting license information file headers.

Microsoft Azure Tools   2.9
Microsoft Azure Tools for Microsoft Visual Studio 2019 - v2.9.30207.1

Microsoft Continuous Delivery Tools for Visual Studio   0.4
Simplifying the configuration of Azure DevOps pipelines from within the Visual Studio IDE.

Microsoft JVM Debugger   1.0
Provides support for connecting the Visual Studio debugger to JDWP compatible Java Virtual Machines

Microsoft Library Manager   2.1.25+gdacdb9b7a1
Install client-side libraries easily to any web project

Microsoft MI-Based Debugger   1.0
Provides support for connecting Visual Studio to MI compatible debuggers

Microsoft Visual C++ Wizards   1.0
Microsoft Visual C++ Wizards

Microsoft Visual Studio Tools for Containers   1.1
Develop, run, validate your ASP.NET Core applications in the target environment. F5 your application directly into a container with debugging, or CTRL + F5 to edit & refresh your app without having to rebuild the container.

Microsoft Visual Studio VC Package   1.0
Microsoft Visual Studio VC Package

Mono Debugging for Visual Studio   16.5.514 (c4f36a9)
Support for debugging Mono processes with Visual Studio.

Node.js Tools   1.5.20122.1 Commit Hash:d74ac73e6e22f9e009948cab4535a26194b19b1b
Adds support for developing and debugging Node.js apps in Visual Studio

NuGet Package Manager   5.5.0
NuGet Package Manager in Visual Studio. For more information about NuGet, visit https://docs.nuget.org/

PHP Tools for Visual Studio   1.32.11706.2019
PHP Tools extend Visual Studio with a set of features to build PHP applications more efficiently. It makes code more readable, easier to navigate, and clean.

ProjectServicesPackage Extension   1.0
ProjectServicesPackage Visual Studio Extension Detailed Info

SQL Server Data Tools   16.0.62003.05170
Microsoft SQL Server Data Tools

StopOnFirstBuildError   1.0
StopOnFirstBuildError

Stops a solution build immediately after a project has failed to build.

http://tech.einaregilsson.com/2011/01/06/stop-build-on-first-error-in-visual-studio-2010/

Test Adapter for Boost.Test   1.0
Enables Visual Studio's testing tools with unit tests written for Boost.Test.  The use terms and Third Party Notices are available in the extension installation directory.

Test Adapter for Google Test   1.0
Enables Visual Studio's testing tools with unit tests written for Google Test.  The use terms and Third Party Notices are available in the extension installation directory.

TypeScript Tools   16.0.20225.2001
TypeScript Tools for Microsoft Visual Studio

Visual Basic Tools   3.5.0-beta4-20153-05+20b9af913f1b8ce0a62f72bea9e75e4aa3cf6b0e
Visual Basic components used in the IDE. Depending on your project type and settings, a different version of the compiler may be used.

Visual C++ for Linux Development   1.0.9.29814
Visual C++ for Linux Development

Visual F# Tools 10.8.0.0 for F# 4.7   16.5.0-beta.20181.6+85af456066acd4e76d2bc7821b44a325e46f2fca
Microsoft Visual F# Tools 10.8.0.0 for F# 4.7

Visual Studio Code Debug Adapter Host Package   1.0
Interop layer for hosting Visual Studio Code debug adapters in Visual Studio

Visual Studio Container Tools Extensions (Preview)   1.0
View, manage, and diagnose containers within Visual Studio.

Visual Studio Tools for CMake   1.0
Visual Studio Tools for CMake

Visual Studio Tools for Containers   1.0
Visual Studio Tools for Containers

VisualStudio.DeviceLog   1.0
Information about my package

VisualStudio.Foo   1.0
Information about my package

VisualStudio.Mac   1.0
Mac Extension for Visual Studio

WiX Toolset Visual Studio Extension   1.0.0.4
WiX Toolset Visual Studio Extension version 1.0.0.4
Copyright (c) .NET Foundation and contributors. All rights reserved.

Xamarin   16.5.000.533 (d16-5@9152e1b)
Visual Studio extension to enable development for Xamarin.iOS and Xamarin.Android.

Xamarin Designer   16.5.0.470 (remotes/origin/d16-5@681de3fd6)
Visual Studio extension to enable Xamarin Designer tools in Visual Studio.

Xamarin Templates   16.5.49 (0904f41)
Templates for building iOS, Android, and Windows apps with Xamarin and Xamarin.Forms.

Xamarin.Android SDK   10.2.0.100 (d16-5/988c811)
Xamarin.Android Reference Assemblies and MSBuild support.
    Mono: c0c5c78
    Java.Interop: xamarin/java.interop/d16-5@fc18c54
    ProGuard: xamarin/proguard/master@905836d
    SQLite: xamarin/sqlite/3.28.0@46204c4
    Xamarin.Android Tools: xamarin/xamarin-android-tools/d16-5@9f4ed4b


Xamarin.iOS and Xamarin.Mac SDK   13.16.0.13 (b75deaf)
Xamarin.iOS and Xamarin.Mac Reference Assemblies and MSBuild support.

Solution 1

Restarting the simulator fixed the issue for me.

Solution 2

We had this exact error and it turned out to be an issue with the underlying HTTP implementation of NSURLRequest:

As far as we can tell, when iOS 8/9/10/11 receive an HTTP response with a Keep-Alive header, it keeps this connection to re-use later (as it should), but it keeps it for more than the timeout parameter of the Keep-Alive header (it seems to always keep the connection alive for 30 seconds.)
Then when a second request is sent by the app less than 30 seconds later, it tries to re-use a connection that might have been dropped by the server (if more than the real Keep-Alive has elapsed).

Here are the solutions we have found so far:

  • Increase the timeout parameter of the server above 30 seconds. It looks like iOS is always behaving as if the server will keep the connection open for 30 seconds regardless of the value provided in the Keep-Alive header. (This can be done for Apache by setting the KeepAliveTimeout option.
  • You can simply disable the keep alive mechanism for iOS clients based on the User-Agent of your app (e.g. for Apache: BrowserMatch "iOS 8." nokeepalive in the mod file setenvif.conf)
  • If you don’t have access to the server, you can try sending your requests with a Connection: close header: this will tell the server to drop the connection immediately and to respond without any keep alive headers. BUT at the moment, NSURLSession seems to override the Connection header when the requests are sent (we didn’t test this solution extensively as we can tweak the Apache configuration)

Solution 3

For mine, Resetting content and settings of Simulator works.
To reset the simulator follow the steps:

iOS Simulator -> Reset Content and Settings -> Press Reset (on the
warning which will come)

Solution 4

The iOS 8.0 simulator runtime has a bug whereby if your network configuration changes while the simulated device is booted, higher level APIs (eg: CFNetwork) in the simulated runtime will think that it has lost network connectivity. Currently, the advised workaround is to simply reboot the simulated device when your network configuration changes.

If you are impacted by this issue, please file additional duplicate radars at http://bugreport.apple.com to get it increased priority.

If you see this issue without having changed network configurations, then that is not a known bug, and you should definitely file a radar, indicating that the issue is not the known network-configuration-changed bug.

Solution 5

Opening Charles resolved the issue for me, which seems very strange…

Charles is an HTTP proxy / HTTP monitor / Reverse Proxy that enables a developer to view all of the HTTP and SSL / HTTPS traffic between their machine and the Internet. This includes requests, responses and the HTTP headers (which contain the cookies and caching information).

Related videos on Youtube

How to Fix "Network Connection Lost" error message in Fortnite Chapter 3 Season 2 PC-Windows 8/10/11

09 : 22

How to Fix «Network Connection Lost» error message in Fortnite Chapter 3 Season 2 PC-Windows 8/10/11

iOS : Why NSURLConnection failed with Error Domain=NSURLErrorDomain Code=-1005 "The network connect

01 : 20

iOS : Why NSURLConnection failed with Error Domain=NSURLErrorDomain Code=-1005 «The network connect

Error 1005 Access Denied while opening a website Fix

02 : 21

Error 1005 Access Denied while opening a website Fix

Fix Error 1005 Access Denied While Opening Website

01 : 47

Fix Error 1005 Access Denied While Opening Website

safari can not open the page because the network connection was lost

02 : 02

safari can not open the page because the network connection was lost

The Network Connection Was Lost MacOS Big Sur Fix

00 : 57

The Network Connection Was Lost MacOS Big Sur Fix

How to Fix "Network Connection Lost" in Fortnite Season 2 | Fortnite Kick Out to the Lobby  on Xbox

03 : 31

How to Fix «Network Connection Lost» in Fortnite Season 2 | Fortnite Kick Out to the Lobby on Xbox

Comments

  • I have an application which works fine on Xcode6-Beta1 and Xcode6-Beta2 with both iOS7 and iOS8. But with Xcode6-Beta3, Beta4, Beta5 I’m facing network issues with iOS8 but everything works fine on iOS7. I get the error "The network connection was lost.". The error is as follows:

    Error: Error Domain=NSURLErrorDomain Code=-1005 «The network connection was lost.» UserInfo=0x7ba8e5b0 {NSErrorFailingURLStringKey=, _kCFStreamErrorCodeKey=57, NSErrorFailingURLKey=, NSLocalizedDescription=The network connection was lost., _kCFStreamErrorDomainKey=1, NSUnderlyingError=0x7a6957e0 «The network connection was lost.»}

    I use AFNetworking 2.x and the following code snippet to make the network call:

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager setSecurityPolicy:policy];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    [manager POST:<example-url>
       parameters:<parameteres>
          success:^(AFHTTPRequestOperation *operation, id responseObject) {
              NSLog(@“Success: %@", responseObject);
          } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
              NSLog(@"Error: %@", error);
          }];
    

    I tried NSURLSession but still receive the same error.

    • facing the same issue with iOS 10.0.1 and Xcode 8.

    • I got this error this morning and fixed it just now with a simple and weird solution. The requested server address is wrong, there is no 4xx or 5xx status code returned, it just encountered this issue, not sure what exactly the root cause is. So, please confirm with the backend developers in your team, or you’ll waste a few hours on it.

  • I see the same problem with NSURLSession and NSURLConnection, thats rules out the problem with AFNetworking. Also I found it works with https and failing with http. I still couldn’t find any solution, did you got any resolution ?

  • No resolution have reported as a bug (18072300) will add comment about https working that is good information.

  • could you paste the bug link here? Thanks because I think I have the same problem but I only use the NSURLConnection (and delegates) but I get the same error message

  • Not able to share Apple bug report. Still open and still present in XCODE 6 beta 7. If you file a bug report also that will help with priority.

  • Looks like this issue is on iOS simulator and I tired with actual device it works fine. Further debugging I found problem is about port on iOS simulator, https port 443 works fine and I was using 8080 for http it used to fail. I tried using other port(s) and able to make http call on iOS simulator. Looks like bug in beta Xcode 6, need to wait for stable Xcode 6.

  • I believe the issue is not specific to the simulator (because I can reproduce the problem on a real device), but specific to iOS 8.0 (because I can’t reproduce it on iOS 7.0).

  • I have the exact same problems on both iOS 8 simulator and devices. Some of my POST (and only POST request) got this error. The userInfo is NSErrorFailingURLStringKey = «rcapi.glose.com/oauth/token»; NSUnderlyingError = «Error Domain=kCFErrorDomainCFNetwork Code=-1005 «The operation couldnU2019t be completed. (kCFErrorDomainCFNetwork error -1005.)» UserInfo=0x7a9e1880 {_kCFStreamErrorDomainKey=4, _kCFStreamErrorCodeKey=-4}»; «_kCFStreamErrorCodeKey» = «-4»; «_kCFStreamErrorDomainKey» = 4;

  • I have this issue on a device too.

  • @darren Then it is not the issue that I was referring to. I suggest you file a radar.

  • please include your radar ID so it makes filing duplicates easier

  • What happens if this problem is on the device not the sim? Tried restarting the device, still same error.

  • @SeanClark: see the next answer: rebooting the simulator works because the OS needs to drop dead connection instead of trying to re-use them after they have been dropped by the server. To work around this issue, you can disable the Keep-alive mechanism on the server for the iOS clients, or, if you don’t have access to the server, you can simply try again the same request when it fails (failure should make the OS drop the connection and a fresh one is instantiated when the retry is sent).

  • I’m currently using Xcode 6.2 and what solved it was clicking on iOS Simulator > Reset Settings and Content. Once that finished I quit the simulator and rebuilt and ran my project… everything worked perfectly afterwards.

  • It’s worked for me to reset the simulator but only 10% of the time. I just got a new ISP and it runs kinda weird. This happens all the time now on simulator. Could be the network.

  • I have this problem with Xcode 6.1.1 and iOS8.1 and https. Retrying 400 times does not seem to recover the situation.

  • The problem is still present in Xcode 6.2 and 6.3 beta 4. I have personally not had a problem with any actual device. The problem is with the simulator and for me only affects sites that do not support SSL. Installing the Charles root certificate for the simulator and running Charles as an SSL proxy allows me to connect to all sites required in my apps from the simulator.

  • It also helps to kill the app before the simulator reset and to restart the Mac. I often change places with different wifi spots and this is a procedure that fixes the issue for me.

  • I don’t think there is anything to solve : underlying OS drops connection for a reason legitimate or not. An app should be prepared to deal with it (work offline or whatever). Assuming the SDK in your particular xcode version ain’t buggy of course: as my answer suggests 6.2 was most likely buggy while 6.1.1 was good. Something similar can be observed now when xcode 6.4 seems reasonably stable while 7.0.1 is an alpha grade software. Or so it seems.

  • Resetting simulator didn’t work for me. However starting Charles made issue to disappear. See stackoverflow.com/a/26066764/598057 which suggests using Charles. Very strange but works…

  • I think all those restarting device/simulator or resetting data should look into this answer. To me all of their actions seems to clear cache which actually fixes the issue. So its probably URL Cache issue. I am going to test it now.

  • Thank you so much for your valuable comment. You are right if I upload below 64 kb image’s base64 string it will uploaded successfully.

  • GET and POST with empty body dictionary [:] will cause this error randomly. I am using Python Flask for the backend REST APIs this may be useful too.

Recents

Related

Понравилась статья? Поделить с друзьями:
  • Nstokrnl exe ошибка
  • Nst ошибка на частотнике шнайдер 312
  • Nst atv320 ошибка
  • Nssm exe ошибка приложения
  • Nsqlite3database ошибка city car driving