Nsurlerrordomain ошибка 999 что значит

I have big trouble with NSURLSession when i’ll terminate the App.
I have downloaded the apple sample:
https://developer.apple.com/library/ios/samplecode/SimpleBackgroundTransfer/Introduction/Intro.html

on Apple reference.

When i start download the file download correctly.
When i enter in background the download continues to.
When i terminate the application and i restart the app the application enter in:

- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error

And i catch this error:

The operation couldn't be completed. (NSURLErrorDomain error -999.)

It seems that i cannot restore download when app has been terminated. It’s correct?For proceed with download i must leave application active in background?

Thank you
Andrea

asked Oct 15, 2014 at 16:09

Andrea Bozza's user avatar

Andrea BozzaAndrea Bozza

1,3742 gold badges12 silver badges31 bronze badges

A couple of observations:

  1. Error -999 is kCFURLErrorCancelled.

  2. If you are using NSURLSessionDownloadTask, you can download those in the background using background session configuration, e.g.

    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:kBackgroundIdentifier];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
    

    If not using background session (e.g. you have to use data task, for example), you can use beginBackgroundTaskWithExpirationHandler to request a little time for the app the finish requests in the background before the app terminates.

  3. Note, when using background sessions, your app delegate must respond to handleEventsForBackgroundURLSession, capturing the completion handler that it will call when appropriate (e.g., generally in URLSessionDidFinishEventsForBackgroundURLSession).

  4. How did you «terminate the app»? If you manually kill it (by double tapping on home button, holding down on icon for running app, and then hitting the little red «x»), that will not only terminate the app, but it will stop background sessions, too. Alternatively, if the app crashes or if it is simply jettisoned because foreground apps needed more memory, the background session will continue.

    Personally, whenever I want to test background operation after app terminates, I have code in my app to crash (deference nil pointer, like Apple did in their WWDC video introduction to NSURLSession). Clearly you’d never do that in a production app, but it’s hard to simulate the app being jettisoned due to memory constraints, so deliberately crashing is a fine proxy for that scenario.

answered Oct 15, 2014 at 16:40

Rob's user avatar

i insert this new lines of code:

- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
{
    BLog();

    NSInteger errorReasonNum = [[error.userInfo objectForKey:@"NSURLErrorBackgroundTaskCancelledReasonKey"] integerValue];

    if([error.userInfo objectForKey:@"NSURLErrorBackgroundTaskCancelledReasonKey"] &&
       (errorReasonNum == NSURLErrorCancelledReasonUserForceQuitApplication ||
        errorReasonNum == NSURLErrorCancelledReasonBackgroundUpdatesDisabled))
    {
        NSData *resumeData = error.userInfo[NSURLSessionDownloadTaskResumeData];
        if (resumeData) {
            // resume
            NSURL *downloadURL = [NSURL URLWithString:DownloadURLString];
            NSURLRequest *request = [NSURLRequest requestWithURL:downloadURL];
            if (!self.downloadTask) {
                self.downloadTask = [self.session downloadTaskWithRequest:request];
                         }

            [self.downloadTask resume];
            if (!_session){
               [[_session downloadTaskWithResumeData:resumeData]resume];
                                         }
        }
    }
}

It catch NSURLErrorCancelledReasonUserForceQuitApplication but when the application try to [[_session downloadTaskWithResumeData:resumeData]resume]

reenter again in:

  • (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
    {

and give me again -999 error.

answered Oct 16, 2014 at 15:08

Andrea Bozza's user avatar

Andrea BozzaAndrea Bozza

1,3742 gold badges12 silver badges31 bronze badges

1

I use this configuration

- (NSURLSession *)backgroundSession
{
/*
 Using disptach_once here ensures that multiple background sessions with the same identifier are not created in this instance of the application. If you want to support multiple background sessions within a single process, you should create each session with its own identifier.
 */
    static NSURLSession *session = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration backgroundSessionConfiguration:@"com.example.apple-samplecode.SimpleBackgroundTransfer.BackgroundSession"];
        session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
    });
    return session;
}

let me explain what i mean with «terminate the app» (in ios8):

  • double tap on home button
  • swipe on my open app.
  • app disappear from open app list
  • relaunch app.

When i reopen the app i enter into callback with error

The operation couldn't be completed. (NSURLErrorDomain error -999.)

There is something that i can’t understand. This behaviour make me crazy! :-(

answered Oct 15, 2014 at 21:38

Andrea Bozza's user avatar

Andrea BozzaAndrea Bozza

1,3742 gold badges12 silver badges31 bronze badges

Asked
9 years, 5 months ago

Viewed
7k times

I have found this error:

Error — Error Domain=NSURLErrorDomain Code=-999

The operation couldn’t be completed. (NSURLErrorDomain error -999.)

During load youtube link on my UIWebView first time.

Any idea why this happens?

  • ios
  • uiwebview

Ram G Athreya's user avatar

asked Dec 12, 2013 at 10:14

Tarang's user avatar

TarangTarang

961 silver badge6 bronze badges

2

  • do u have the solution or not yet @Tarang ?

    Mar 23, 2014 at 11:03

1 Answer

-999 error code means NSURLErrorCancelled.
This happens when the past request is cancelled.
If it works without any issues except that, no problem :)

See: Foundation Constants Reference

answered Dec 12, 2013 at 11:05

mono's user avatar

monomono

4,3423 gold badges20 silver badges49 bronze badges

2

  • so what it is the solution ? when user kill the app the request is cancelled. so what i can do ?

    Mar 23, 2014 at 11:02

  • This error, crashing my app, please let me provide a solution.

    Jun 15, 2015 at 5:09

  • The Overflow Blog
  • Featured on Meta

Linked

Related

Hot Network Questions

  • What happens in heaven if you remarry?

  • Vampire movie with vampires like in «30 Days of Night»

  • Is it possible for rockets to exist in a world that is only in the early stages of developing jet aircraft?

  • Should I trust my own thoughts when studying philosophy?

  • How do I troubleshoot a zfs dataset that the server when the server can’t agree if it’s mounted or not?

  • Cancel circled text under circledsteps?

  • Does electric field have a speed itself?

  • Two attempts of an if with an «and» are failing: if [ … ] -a [ … ] , if [[ … && … ]] Why?

  • How can an accidental cat scratch break skin but not damage clothes?

  • Decidability of completing Penrose tilings

  • What are some ways to check if a molecular simulation is running properly?

  • Why doesn’t SpaceX sell Raptor engines commercially?

  • Why do I get different sorting for the same query on the same data in two identical MariaDB instances?

  • Ways to find safe route in flooded roads

  • How to read a NFC card with USB reader

  • What are good reasons to create a city/nation in which a government wouldn’t let you leave

  • Noise cancels but variance sums — contradiction?

  • Running AC with dye permanently

  • Diagonalizing selfadjoint operator on core domain

  • Can I also say: ‘ich tut mir leid’ instead of ‘es tut mir leid’?

  • Does substituting electrons with muons change the atomic shell configuration?

  • Indian Constitution — What is the Genesis of this statement? » ‘Union of India’ should be distinguished from the expression ‘territory of India’ »

  • Lilypond (v2.24) macro delivers unexpected results

  • Drawing octet diagram in latex

more hot questions

Question feed

Your privacy

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

The NSURLErrorDomain error code -999 in iOS is a common issue that developers face when trying to make network requests. This error occurs when a request is cancelled before it is completed, and it can have a variety of root causes such as network connectivity issues, incorrect request configuration, or incorrect usage of the API. Solving this issue requires a deeper understanding of the problem and a systematic approach to finding the solution. In this article, we’ll outline several methods for fixing the NSURLErrorDomain error code -999 in iOS, so you can get your network requests working as expected.

Method 1: Retry the Request

To fix the NSURLErrorDomain error code -999 in iOS, you can retry the request. Here’s an example of how to do it in Swift:

func retryRequest(request: URLRequest, session: URLSession, completion: @escaping (Data?, URLResponse?, Error?) -> Void) {
    var request = request
    request.cachePolicy = .reloadIgnoringLocalCacheData
    
    let task = session.dataTask(with: request) { (data, response, error) in
        if let error = error as NSError?, error.domain == NSURLErrorDomain && error.code == NSURLErrorCancelled {
            // Retry the request
            retryRequest(request: request, session: session, completion: completion)
        } else {
            completion(data, response, error)
        }
    }
    
    task.resume()
}

This function takes a URLRequest, a URLSession, and a completion handler as parameters. It first sets the request’s cache policy to ignore local cache data. Then, it creates a data task with the session and the modified request. In the task’s completion handler, it checks if the error is the NSURLErrorCancelled error. If it is, it recursively calls itself with the same request and session to retry the request. Otherwise, it calls the completion handler with the data, response, and error.

To use this function, you can simply call it with your original request and session:

let request = URLRequest(url: url)
let session = URLSession.shared

retryRequest(request: request, session: session) { (data, response, error) in
    // Handle the response
}

This will retry the request if it encounters the -999 error code.

Method 2: Check Network Connectivity

To fix the NSURLErrorDomain error code -999 in iOS, we can use the «Check Network Connectivity» method. This method checks whether the device is connected to a network or not. If the device is not connected to a network, then we can show an alert message to the user. Here are the steps to implement this method:

  1. Import the SystemConfiguration framework:
import SystemConfiguration
  1. Create a function to check network connectivity:
func isInternetAvailable() -> Bool {
    var zeroAddress = sockaddr_in()
    zeroAddress.sin_len = UInt8(MemoryLayout.size(ofValue: zeroAddress))
    zeroAddress.sin_family = sa_family_t(AF_INET)
    let defaultRouteReachability = withUnsafePointer(to: &zeroAddress) {
        $0.withMemoryRebound(to: sockaddr.self, capacity: 1) {zeroSockAddress in
            SCNetworkReachabilityCreateWithAddress(nil, zeroSockAddress)
        }
    }
    var flags = SCNetworkReachabilityFlags()
    if !SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) {
        return false
    }
    let isReachable = flags.contains(.reachable)
    let needsConnection = flags.contains(.connectionRequired)
    return (isReachable && !needsConnection)
}
  1. Call the function to check network connectivity before making a request:
if isInternetAvailable() {
    // Make request
} else {
    // Show alert message
}

By following these steps, we can fix the NSURLErrorDomain error code -999 in iOS using the «Check Network Connectivity» method.

Method 3: Configure the Request Correctly

To fix the NSURLErrorDomain error code -999 in iOS, you can configure the request correctly. Here are the steps to do it:

  1. Create an NSURLSession object with a default configuration:
let session = URLSession(configuration: .default)
  1. Create an NSURL object with the URL you want to request:
let url = URL(string: "https://www.example.com")!
  1. Create an NSURLRequest object with the URL and set the HTTP method to GET:
var request = URLRequest(url: url)
request.httpMethod = "GET"
  1. Create an NSURLSessionDataTask object with the request and a completion handler:
let task = session.dataTask(with: request) { (data, response, error) in
    // Handle the response or error
}
  1. Start the task:

Here’s the complete code:

let session = URLSession(configuration: .default)
let url = URL(string: "https://www.example.com")!
var request = URLRequest(url: url)
request.httpMethod = "GET"
let task = session.dataTask(with: request) { (data, response, error) in
    // Handle the response or error
}
task.resume()

This code creates a URLSession object with a default configuration, creates an NSURL object with the URL you want to request, creates an NSURLRequest object with the URL and sets the HTTP method to GET, creates an NSURLSessionDataTask object with the request and a completion handler, and starts the task.

By following these steps, you can configure the request correctly and fix the NSURLErrorDomain error code -999 in iOS.

Method 4: Avoid Cancelling the Request

To fix the NSURLErrorDomain error code -999 in iOS, you can avoid cancelling the request. Here are the steps:

  1. Declare a property for your URLSession:
  1. Create a URLSession configuration and set it to your property:
let config = URLSessionConfiguration.default
session = URLSession(configuration: config)
  1. Create a URL object from your URL string:
let url = URL(string: "your_url_string_here")
  1. Create a URLRequest object from your URL:
var request = URLRequest(url: url!)
  1. Set the HTTP method for your request:
request.httpMethod = "GET"
  1. Create a URLSessionDataTask and resume it:
let task = session?.dataTask(with: request) { data, response, error in
    if let error = error {
        print("Error: (error)")
        return
    }
    
    // Handle your data and response here
}
task?.resume()

By avoiding cancelling the request, you can ensure that your request is completed and you won’t receive the -999 error code.

Method 5: Use a Different API

To fix the NSURLErrorDomain error code -999 in iOS, you can try using a different API. Here’s an example of how to do it in Swift:

Step 1: Import the necessary modules

import Foundation
import UIKit

Step 2: Create a URL object with the new API

let url = URL(string: "https://api.example.com/new-api-endpoint")

Step 3: Create a URL request with the new URL

let request = URLRequest(url: url!)

Step 4: Create a URLSession and perform the request

let session = URLSession.shared
let task = session.dataTask(with: request) { (data, response, error) in
    // Handle the response
}
task.resume()

By using a different API, you can avoid the NSURLErrorDomain error code -999 and successfully retrieve the data you need.

Я пытался использовать API Facebook Corona SDK, чтобы опубликовать оценку игры, которую я разрабатываю, на facebook. Однако у меня с этим проблема. В первый раз, когда я пытаюсь отправить сообщение в facebook, я получаю эту ошибку после входа в систему и аутентификации пользователя:

Код ошибки NSURLErrorDomain -999

Тогда он не будет публиковаться на Facebook. Каковы возможные причины этой ошибки и как ее исправить? Я попытался выполнить поиск в Интернете, но не смог найти информацию об этом. Заранее спасибо.

Кстати, я не использую веб-просмотр в своем приложении. Просто api виджета и слушатель show_dialog в моем классе Facebook.

12 ответов

Лучший ответ

Ошибка задокументирована в библиотеке разработчика Mac (документы iOS)

Соответствующий сегмент из документации будет:

Коды ошибок системы загрузки URL

Эти значения возвращаются как свойство кода ошибки объекта NSError с доменом «NSURLErrorDomain».

enum
{
   NSURLErrorUnknown = -1,
   NSURLErrorCancelled = -999,
   NSURLErrorBadURL = -1000,
   NSURLErrorTimedOut = -1001,

Как вы видете; -999 вызвано ErrorCancelled . Это означает: другой запрос сделан до того, как предыдущий запрос будет выполнен.


146

hjpotter92
23 Дек 2019 в 12:24

Hjpotter92 абсолютно прав, я просто хочу предложить решение для своего случая. Надеюсь, это будет полезно и для вас. Вот моя ситуация:

На странице входа в систему> нажмите вход> всплывающее диалоговое окно загрузки> вызовите журнал в службе> диалоговое окно отклонения> нажмите другой экран> вызовите другую службу -> вызовите ошибку -999

Чтобы исправить это, я поставил задержку между закрытием диалогового окна и нажатием нового экрана:

    [indicatorAlert dismissWithClickedButtonIndex:0 animated:YES];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.01 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
                [self performSegueWithIdentifier:@"HomeSegue" sender:nil];
            });

Странно, что эта проблема возникает только на iOS 7.


11

thanhbinh84
29 Ноя 2013 в 11:31

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


6

Pablo Blanco
8 Июл 2019 в 10:34

Просто хотел добавить здесь, что при получении -999 "cancelled" проблема обычно заключается в одном из двух:

  • Вы снова выполняете тот же запрос.
  • Вы поддерживаете слабую ссылку на ваш объект manager, который преждевременно освобождается. (Создайте сильную ссылку)


12

Ramon
23 Авг 2019 в 21:47

Помимо того, что написал Рамон, существует третья возможная причина получения NSURLErrorDomain -999 cancelled:

Вы отменили задачу во время ее выполнения, либо вызвав .cancel() для объекта задачи данных, либо потому, что вы использовали .invalidateAndCancel() для объекта сеанса. Если вы создаете настраиваемый сеанс с делегатом, вам следует вызвать .invalidateAndCancel() или .finishTasksAndInvalidate(), чтобы разрешить сильную ссылку между сеансом и его делегатом, как указано в Документация разработчика Apple:

Объект сеанса сохраняет сильную ссылку на делегата до тех пор, пока ваше приложение не выйдет или не аннулирует сеанс явным образом. Если вы не аннулируете сеанс, ваше приложение будет терять память до завершения работы.

Если вас интересует такое поведение журнала, я нашел следующее объяснение на форумах разработчиков Apple :

В качестве пояснения, еще в iOS 10 мы представили новую общесистемную архитектуру ведения журнала (смотрите WWDC 2016 Session 721 Unified Logging and Activity Tracing для подробностей) и многие подсистемы, включая CFNetwork, находятся в процессе перехода к этому. Пока этот ход не будет полностью завершен, вы столкнетесь с некоторыми странными крайними случаями, подобными этому.


2

Chris Graf
24 Авг 2019 в 10:56

В приложении нашей компании много ошибок -999 в iOS. Я поискал, нашел, что у причины две, например, сетевая задача была освобождена или сертификат недействителен. Но я проверил наш код, эти два невозможны. Я использую Alamofire, который использует URLSession. К счастью, сеть Android-приложения нашей компании в норме. Итак, проверяем разницу. Мы обнаружили, что http-запрос от iOS — Http2.0, а android — Http1.1. Таким образом, мы принудительно понижаем версию поддержки HTTP до http1.1, после чего уменьшается количество ошибок -999 !!!

Я думаю, что в URL-сеансе Apple может быть какая-то ошибка. Проверьте ссылку New NSURLSession для каждого излишка DataTask? для некоторых подробных мыслей.


1

Dan Lee
26 Июл 2019 в 06:47

Я не использовал API Facebook Corona SDK, но я столкнулся с этой проблемой при использовании Alamofire, secondRequest всегда отменяется при выполнении с ошибкой -999, согласно сообщениям, которые я нашел в Интернете, причина в том, что session свойство равно deinit до завершения асинхронной работы, поскольку оно находится вне области видимости, я, наконец, решил эту проблему с помощью deinit свойства сеанса вручную, чтобы компилятор не деинициализировал его в неправильной позиции:

class SessionManager {
    var session:SessionManager?

    init() {
        self.session = SessionManager(configuration:URLSessionConfiguration.ephemeral)
    }
    private func firstRequest() {
        guard let session = self.session else {return}
        session.request(request_url).responseData {response in
            if let data=response.data {
                self.secondRequest()
            }
    }
    private func secondRequest() {
        guard let session = self.session else {return}
        session.request(request_url).responseData {response in
            if let data=response.data {
                self.secondRequest()
            }
            //session will no longer be needed, deinit it
            self.session = nil
    }

    }


2

ilovecomputer
22 Дек 2017 в 02:07

Установите флажок «Если вы звоните cancel() на URLSessionDataTask«, чтобы исправить

NSURLErrorDomain Code=-999 "cancelled"


1

yoAlex5
25 Окт 2020 в 20:57

Я получал эту ошибку в версии приложения Xamarin для iOS. Не уверен в основной причине, но в моем случае удалось обойти ее, используя метод post вместо get для чего-либо, передавая контекст сервера в теле запроса — что в любом случае имеет больше смысла. Android / Windows / служба все обрабатывает GET с контентом, но в приложении iOS будет частично не отвечать, а затем выплюнуть материал 999 NSUrlErrorDomain в журнале. Надеюсь, это поможет кому-то другому столкнуться с этим. Я предполагаю, что сетевой код застревает в цикле, но не могу увидеть рассматриваемый код.


0

Victor Thomas Wilcox Jr.
12 Сен 2019 в 22:39

Оказалось, что в моем проекте Cordova (или аналогичном) это была проблема с плагином . Убедитесь, что вы не упустили ни одного плагина, и убедитесь, что он установлен правильно и без проблем.

Самый простой способ проверить это — просто начать все сначала, воссоздав проект Cordova (cordova create <path>) вместе с необходимыми платформами (cordova platform add <platform name>), и добавить каждый плагин с подробным флагом ( —verbose), чтобы вы могли видеть, если что-то пошло не так в журнале консоли, пока плагин загружается, добавляется в проект и устанавливается для каждой платформы (cordova plugin add cordova-plugin-device --verbose)

Резюме: cordova create <path> cordova platform add <platform name> cordova plugin add cordova-plugin-device --verbose


0

Vyrnach
1 Окт 2019 в 11:08

В моем случае я использовал сообщение о загрузке, для которого не требовалось содержимое тела:

// The `from: nil` induces error "cancelled" code -999
let task = session.uploadTask(with: urlRequest, from: nil, completionHandler: handler)

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

let task = session.uploadTask(with: urlRequest, from: Data(), completionHandler: handler)

В документации фреймворка не указано, почему from bodyData является необязательным типом или что происходит, когда он равен нулю.


0

dlalpine
11 Авг 2021 в 20:43

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

extension WebViewController: WKNavigationDelegate {
    func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
        webView.reload()
    }
}


0

Edgardo Agno
21 Мар 2022 в 12:39



Я пытался использовать Facebook API Corona SDK, чтобы опубликовать счет в игре, которую я разрабатываю на facebook. Однако, у меня возникли проблемы с ним. В первый раз, когда я пытаюсь опубликовать в facebook, я получаю эту ошибку после входа в систему и аутентификации пользователя:

код ошибки NSURLErrorDomain -999

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

кстати, я не использую webview в своем приложении. Просто виджет api и слушатель show_dialog в моем классе Facebook.


846  


3  

3 ответов:

ошибка была задокументирована на Библиотека Разработчиков Mac(iOS docs)

соответствующий сегмент из документации будет:

URL загрузка системных кодов ошибок

эти значения возвращаются как свойство кода ошибки NSError
объект с доменом «NSURLErrorDomain».

enum
{
   NSURLErrorUnknown = -1,
   NSURLErrorCancelled = -999,
   NSURLErrorBadURL = -1000,
   NSURLErrorTimedOut = -1001,

Как видите; -999 причинена ErrorCancelled. Это означает: другой запрос выполняется до завершения предыдущего запроса.

hjpotter92 абсолютно прав, я просто хочу предоставить решение для моего случая. Надеюсь, это полезно и для вас. Вот моя ситуация:

на странице входа > нажмите вход > всплывающее окно загрузки > вызовите службу > закрыть диалог > нажмите другой экран > вызовите другую службу — > вызовите ошибку -999

чтобы исправить это, я поставил задержку между отклонением диалога и нажатием нового экрана:

    [indicatorAlert dismissWithClickedButtonIndex:0 animated:YES];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.01 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
                [self performSegueWithIdentifier:@"HomeSegue" sender:nil];
            });

странно, что эта проблема происходит только на iOS 7.

Я не использовал Facebook API Corona SDK, но я столкнулся с этой проблемой при использовании Alamofire,secondRequest всегда отменяйте в исполнении с ошибкой -999, согласно сообщениям, которые я нашел в интернете, причина в том, что session недвижимость deinit перед завершением асинхронной работы, так как она выходит за рамки, я, наконец, решил эту проблему с помощью deinit свойства сессии вручную, поэтому компилятор не деинициализации его в неправильном положении:

class SessionManager {
    var session:SessionManager?

    init() {
        self.session = SessionManager(configuration:URLSessionConfiguration.ephemeral)
    }
    private func firstRequest() {
        guard let session = self.session else {return}
        session.request(request_url).responseData {response in
            if let data=response.data {
                self.secondRequest()
            }
    }
    private func secondRequest() {
        guard let session = self.session else {return}
        session.request(request_url).responseData {response in
            if let data=response.data {
                self.secondRequest()
            }
            //session will no longer be needed, deinit it
            self.session = nil
    }

    }

Понравилась статья? Поделить с друзьями:
  • Nsurlerrordomain ошибка 1005
  • Nsunsr ошибка при запуске 0xc0000906
  • Nsunsr exe системная ошибка
  • Nsunsr exe ошибка приложения 0xc0000906
  • Nsuns4 exe ошибка при запуске приложения 0xc0000142