Ошибка nsurlerrordomain 999

Throwing «Операция не может быть выполнена. (Ошибка NSURLErrorDomain -999.)» В методе WKNavigationDelegate webView (_ webView: WKWebView, didFail navigation: WKNavigation !, withError ...

Интерфейс подобен контракту, в котором вы хотите, чтобы ваш класс реализации реализовал методы, написанные в контракте (интерфейс). Поскольку Java не предоставляет множественное наследование, программирование для интерфейса является хорошим способом достижения цели множественного наследования. Если у вас есть класс A, который уже расширяет какой-либо другой класс B, но вы хотите, чтобы класс A также следовал определенным рекомендациям или реализовывал определенный контракт, тогда вы можете сделать это путем программирования стратегии интерфейса.

задан hjpotter92 6 October 2015 в 08:02

поделиться

3 ответа

Ошибка зарегистрирована в Mac Developer Library (iOS docs)

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

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

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

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

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

ответ дан hjpotter92 21 August 2018 в 17:23

поделиться

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

    }

ответ дан luiyezheng 21 August 2018 в 17:23

поделиться

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.

ответ дан thanhbinh84 21 August 2018 в 17:23

поделиться

Другие вопросы по тегам:

Похожие вопросы:

I am trying to update my iPhone app to work with OS 3.0. I have a UIWebView that shows a page fine. But when I click a link it calls my delegate for didFailLoadWithError and the error is Operation could not be completed. (NSURLErrorDomain error -999.) I verified this is still working with OS 2.2.1, so it is something changed in 3.0.

Any ideas?

dlamblin's user avatar

dlamblin

43.6k20 gold badges101 silver badges138 bronze badges

asked Jun 21, 2009 at 21:05

dp.'s user avatar

3

I was able to find the answer here.

This thread contained this description for this error: This error may occur if an another request is made before the previous request of WebView is completed...

I worked around this by ignoring this error and letting the webview continue to load.

if ([error code] != NSURLErrorCancelled) {
//show error alert, etc.
}

BadPirate's user avatar

BadPirate

25.6k10 gold badges91 silver badges122 bronze badges

answered Jun 27, 2009 at 18:56

dp.'s user avatar

dp.dp.

1,7412 gold badges11 silver badges8 bronze badges

5

NSURLErrorCancelled (-999)

«Returned when an asynchronous load is canceled. A Web Kit framework delegate will receive this error when it performs a cancel operation on a loading resource. Note that an NSURLConnection or NSURLDownload delegate will not receive this error if the download is canceled.»

For my situation (and probably yours) this can be ignored:

if([error code] == NSURLErrorCancelled) return; // Ignore this error

answered Nov 10, 2010 at 18:05

BadPirate's user avatar

BadPirateBadPirate

25.6k10 gold badges91 silver badges122 bronze badges

The above TWO replies was CORRECT>
Just do a return if the loading request causes cancellation.

Also I want to point out that, people do NOT forget to put an NSLog inside your didFailLoadWithError method, this can prevent losing a lot of time by spotting the issue right on!

So here is the final solution with all I mentioned above:

-(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
    NSLog(@"ERROR : %@",error); //Get informed of the error FIRST
    if([error code] == NSURLErrorCancelled) 
        return;
}

answered Apr 23, 2013 at 11:32

Khayrattee Wasseem's user avatar

I am trying to update my iPhone app to work with OS 3.0. I have a UIWebView that shows a page fine. But when I click a link it calls my delegate for didFailLoadWithError and the error is Operation could not be completed. (NSURLErrorDomain error -999.) I verified this is still working with OS 2.2.1, so it is something changed in 3.0.

Any ideas?

dlamblin's user avatar

dlamblin

43.6k20 gold badges101 silver badges138 bronze badges

asked Jun 21, 2009 at 21:05

dp.'s user avatar

3

I was able to find the answer here.

This thread contained this description for this error: This error may occur if an another request is made before the previous request of WebView is completed...

I worked around this by ignoring this error and letting the webview continue to load.

if ([error code] != NSURLErrorCancelled) {
//show error alert, etc.
}

BadPirate's user avatar

BadPirate

25.6k10 gold badges91 silver badges122 bronze badges

answered Jun 27, 2009 at 18:56

dp.'s user avatar

dp.dp.

1,7412 gold badges11 silver badges8 bronze badges

5

NSURLErrorCancelled (-999)

«Returned when an asynchronous load is canceled. A Web Kit framework delegate will receive this error when it performs a cancel operation on a loading resource. Note that an NSURLConnection or NSURLDownload delegate will not receive this error if the download is canceled.»

For my situation (and probably yours) this can be ignored:

if([error code] == NSURLErrorCancelled) return; // Ignore this error

answered Nov 10, 2010 at 18:05

BadPirate's user avatar

BadPirateBadPirate

25.6k10 gold badges91 silver badges122 bronze badges

The above TWO replies was CORRECT>
Just do a return if the loading request causes cancellation.

Also I want to point out that, people do NOT forget to put an NSLog inside your didFailLoadWithError method, this can prevent losing a lot of time by spotting the issue right on!

So here is the final solution with all I mentioned above:

-(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
    NSLog(@"ERROR : %@",error); //Get informed of the error FIRST
    if([error code] == NSURLErrorCancelled) 
        return;
}

answered Apr 23, 2013 at 11:32

Khayrattee Wasseem's user avatar

I’ve been trying to use Corona SDK’s Facebook API to post the score on the game I’m developing on facebook. However, I’m having a problem with it. During the first time I try to post to facebook, I get this error after login and user authentication:

NSURLErrorDomain error code -999

Then, it won’t post on facebook. What are possible causes of this error and how can I address it?

By the way, I am not using webview on my app. Just the widget api and a show_dialog listener in my Facebook class.

user's user avatar

user

5,2576 gold badges19 silver badges35 bronze badges

asked Apr 18, 2013 at 2:27

user1597438's user avatar

The error has been documented on the Mac Developer Library(iOS docs)

The concerned segment from the documentation will be:

URL Loading System Error Codes

These values are returned as the error code property of an NSError
object with the domain “NSURLErrorDomain”.

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

As you can see; -999 is caused by ErrorCancelled. This means: another request is made before the previous request is completed.

answered Apr 18, 2013 at 6:38

hjpotter92's user avatar

hjpotter92hjpotter92

77.3k35 gold badges141 silver badges178 bronze badges

13

Just wanted to add here, when receiving a -999 "cancelled" the problem usually is one of two things:

  • You’re executing the exact same request again.
  • You’re maintaining a weak reference to your manager object that gets deallocated prematurely. (Create strong reference)

answered Jan 14, 2019 at 9:34

Ramon's user avatar

RamonRamon

1,3758 silver badges16 bronze badges

5

hjpotter92 is absolutely right, I just want to provide solution for my case. Hopefully it is useful for you as well. Here is my situation:

On log in page > press log in > pop up loading dialog > call log in service > dismiss dialog > push another screen > call another service —> cause error -999

To fix it, I put a delay between dismissing dialog and pushing new screen:

    [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];
            });

It is strange that this issue happens on iOS 7 only.

answered Nov 29, 2013 at 7:31

thanhbinh84's user avatar

thanhbinh84thanhbinh84

17.5k5 gold badges60 silver badges69 bronze badges

3

I have faced the same error with Alamofire and it was because the certificate pinning.
The certificate wasn’t valid anymore, so I had to remove it and add the new one.
Hope it helps.

answered Jul 4, 2019 at 10:31

Pablo Blanco's user avatar

I didn’t use Corona SDK’s Facebook API but I encountered this problem when using Alamofire, the secondRequest always cancel in execution with the error -999, according to the posts I found on internet, the reason is that session property is deinit before completion of async work since it is out of the scope, I finally solved this problem by deinit the session property manually so the compiler won’t deinit it at wrong position:

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
    }

    }

answered Dec 21, 2017 at 23:07

ilovecomputer's user avatar

ilovecomputerilovecomputer

4,0181 gold badge20 silver badges33 bronze badges

1

In addition to what Ramon wrote, there is a third possible reason when receiving a NSURLErrorDomain -999 cancelled:

You cancelled the task while it was executing either by calling .cancel() on the datatask object or because you used .invalidateAndCancel() on the session object. If you are creating a custom session with a delegate, you should call .invalidateAndCancel() or .finishTasksAndInvalidate() to resolve the strong reference between the session and its delegate, as mentioned in the Apple Developer Documentation:

The session object keeps a strong reference to the delegate until your app exits or explicitly invalidates the session. If you don’t invalidate the session, your app leaks memory until it exits.

If you are wondering about this logging behaviour, I found the following explanation in the Apple Developer forums:

By way of explanation, back in iOS 10 we introduced a new logging system-wide logging architecture (watch WWDC 2016 Session 721 Unified Logging and Activity Tracing for the details) and lots of subsystem, including CFNetwork, are in the process of moving over to that. Until that move is fully finished you’re going to encounter some weird edge cases like this one.

answered Aug 24, 2019 at 7:56

Chris Graf's user avatar

Chris GrafChris Graf

1,7891 gold badge15 silver badges33 bronze badges

Our company’s app has many -999 error in iOS. I have searched around, find the reason has two, like the network task has been dealloc or the certificate isn’t valid. But I have checked our code, these two aren’t possible. I am using Alamofire
which is using URLSession. Luckily, our company’s android app’s network is normal. So we check the difference. We found the http request from iOS is Http2.0, while android is Http1.1. So we force the backend http support version down to http1.1, then -999 error count descends!!!

I think there maybe some bug in Apple’s URLSession. Check the link New NSURLSession for every DataTask overkill? for some detail thoughts

answered Jul 26, 2019 at 3:47

Dan Lee's user avatar

Dan LeeDan Lee

811 silver badge5 bronze badges

Please check If you call cancel() on URLSessionDataTask to fix

NSURLErrorDomain Code=-999 "cancelled"

answered Oct 25, 2020 at 17:57

yoAlex5's user avatar

yoAlex5yoAlex5

26.6k8 gold badges180 silver badges191 bronze badges

I was getting this error in iOS specific version of Xamarin app. Not sure the underlying cause, but in my case was able to work around it by using post method instead of get for anything passing the server context in the request body — which makes more sense anyway. Android / Windows / the service all handle the GET with content, but in iOS app will become partially unresponsive then spit out the 999 NSUrlErrorDomain stuff in the log. Hopefully, that helps someone else running into this. I assume the net code is getting stuck in a loop, but could not see the code in question.

answered Sep 12, 2019 at 19:39

Victor Thomas Wilcox Jr.'s user avatar

For my Cordova project (or similar), turns out it was a plugin issue. Make sure you’re not missing any plugins and make sure they’re installed properly without issue.

Easiest way to verify this is simply to start fresh by recreating the Cordova project (cordova create <path>) along with the required platforms (cordova platform add <platform name>) and add each plugin with the verbose flag (—verbose) so that you can see if anything went wrong in the console log while the plugin is being downloaded, added to project and installed for each platform (cordova plugin add cordova-plugin-device --verbose)

Recap:
cordova create <path>
cordova platform add <platform name>
cordova plugin add cordova-plugin-device --verbose

answered Oct 1, 2019 at 8:03

Vyrnach's user avatar

VyrnachVyrnach

1191 silver badge9 bronze badges

For my case, I used an upload task post that did not need body contents:

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

The fix is to use zero byte data instead of nil,

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

The framework documentation doesn’t specify why the from bodyData is an optional type, or what happens when it is nil.

answered Aug 11, 2021 at 17:43

dlalpine's user avatar

We solved this problem by reloading the web view when it failed loading.

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

answered Mar 21, 2022 at 9:39

Edgardo Agno's user avatar

Содержание

  1. Alamofire: [Result]: FAILURE: Error Domain=NSURLErrorDomain Code=-999 «cancelled»
  2. 6 Answers 6
  3. Error Domain=NSURLErrorDomain Code=-999 «cancelled» #157
  4. Comments
  5. How to fix «NSURLErrorDomain error code -999» in iOS
  6. 12 Answers 12
  7. URL Loading System Error Codes
  8. NSURLErrorDomain error -999
  9. Устраняем предупреждения в админ панели NextCloud
  10. Индексирование файлов
  11. Предупреждения о текущей конфигурации /.well-known/.
  12. Зависание входа в панель NextCloud
  13. Не настроена система кэширования.
  14. Модуль php-imagick не поддерживает SVG
  15. Не указан регион размещения этого сервера Nextcloud
  16. Предупреждение headers
  17. Заголовок HTTP «Strict-Transport-Security»
  18. PHP не настроен для системного окружения.
  19. Значение PHP ниже рекомендуемого значения .
  20. Не скачиваются файлы больше 1Гб

Alamofire: [Result]: FAILURE: Error Domain=NSURLErrorDomain Code=-999 «cancelled»

The service I’m connecting to is using a self signed certificate. For dev purposes I do not want to validate that chain.

Using swift 3 with Alamofire 4. Fixed the ATS accordingly:

Code to connect and disable evaluation.

Error log from dumpPrint

URL has been masked.

6 Answers 6

To retain SessionManager instance you need to capture it in closure passed to responseJSON :

Otherwise sessionManager is deallocated shortly it goes out of scope and any executing requests are cancelled.

Please add this statement to the end of responseJson block:

It happens if the object of the manager is not retained till execution of the block completes, so this would ensure its retention.

Just put the method of invalidate after task finish, means session.finishTasksAndInvalidate()

Please check in sessiondidReceiveChallenge: delegate implementation of NSURLSession . Chances are NSURLSessionAuthChallengeCancelAuthenticationChallenge is getting executed somewhere.

You need to properly manage the lifetime of your SessionManager instance. Most commonly this is done by making a singleton instance. Otherwise, when your manager goes out of scope and is deinit ed, all outstanding requests will be cancelled.

There could be a lot of reason to why your requests «cancelled».
In your case your request cancels immediately. You can refer to this issue in Alamofire repository issues

jshier commented on Oct 10, 2016

An unexpected error -999 almost always means your SessionManager was deallocated, cancelling any ongoing requests. I suggest you create a singleton value for your custom SessionManager, or perhaps just reevaluate if you really need one.

if you create a singleton value for your object it remains in memory and prevent from deallocate

and another thing that i avoid is to name your variables diffrent, a sessionManager is in Alamofire and your variable is also called sessionManager.

Источник

Error Domain=NSURLErrorDomain Code=-999 «cancelled» #157

I want to create a custom manager instance and use it:

Which gives me an error:
Error Domain=NSURLErrorDomain Code=-999 «cancelled»

If i try this with the Singleton it works fine:

Shouldn’t the above code work with a custom instanced manager, too?

Thanks in advance.

The text was updated successfully, but these errors were encountered:

The difference here is that the initialized manager is not owned, and is deallocated shortly after it goes out of scope. As a result, any pending tasks are cancelled.

So about this issue how to implementation modified configuration with manager instead of using default configuration with sharedInstance?

I had the same problem, is there a way to set up a specific session manager for modification instead of modifying the global default one?

@cloud-hot @kohakugawa You just have to ensure that manager is retained. There are lots of ways you can do this. At the simplest level, for example, you could make it a stored property for a custom NetworkManager class:

@rainypixels , Thanks! I will try it later.

After trying all the solutions provided above, my code still fails with same error. For my case, it’s because I made too many requests within same session, which exceed the maximum limit (https://developer.apple.com/library/ios/documentation/Foundation/Reference/NSURLSessionConfiguration_class/#//apple_ref/occ/instp/NSURLSessionConfiguration/HTTPMaximumConnectionsPerHost).

let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
configuration.HTTPMaximumConnectionsPerHost = 10 // Some arbitrary number that I feel big enough.
let manager = Alamofire.Manager(configuration: configuration)

Error Domain=NSURLErrorDomain Code=-999 «cancelled» UserInfo=0x78fc41e0

Can you print out the sample request using the debugprint()

-(NSURLSessionDataTask *)logingUser:(NSString *)user password:(NSString *)password completion:(void (^)(NSDictionary *results, NSError *error))completion <
NSURLSessionDataTask *task = [self POST:kBASE_URL
parameters:@<@»request» : @»login»>
constructingBodyWithBlock:^(id formData) <
[formData appendPartWithFormData:[user dataUsingEncoding:NSUTF8StringEncoding] name:@»user»];
[formData appendPartWithFormData:[password dataUsingEncoding:NSUTF8StringEncoding] name:@»password»];
>
success:^(NSURLSessionDataTask *task, id responseObject) <
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)task.response;
if (httpResponse.statusCode == 200) <
dispatch_async(dispatch_get_main_queue(), ^ <
completion(responseObject, nil);
>);
> else <
dispatch_async(dispatch_get_main_queue(), ^ <
NSLog(@»Received HTTP %ld», (long)httpResponse.statusCode);
completion(nil, nil);
>);
>
> failure:^(NSURLSessionDataTask *task, NSError *error) <
dispatch_async(dispatch_get_main_queue(), ^ <
NSLog(@»ERROR: %@», [Utility localize:@»Connection_Error»]);
NSLog(@»ERROR-LOG: %@»,error);
completion(nil, error);
>);
>];
return task;
>

ERROR: Could not connect to the server

Error Domain=NSURLErrorDomain Code=-999 «cancelled» UserInfo=0x78fc41e0

Are you sure your url is correct, since the address (https://vodafoneplazaapp.vodafone.es:20000/api.php) shows no endpoint.

that is the URL, but managed not find the error in my code

I have the same issue. When I configured the Security Policies:

I got this error:

and when I disable the security policies, it works. What could it be the problem? The certificate? The server configuration?

Источник

How to fix «NSURLErrorDomain error code -999» in iOS

I’ve been trying to use Corona SDK’s Facebook API to post the score on the game I’m developing on facebook. However, I’m having a problem with it. During the first time I try to post to facebook, I get this error after login and user authentication:

NSURLErrorDomain error code -999

Then, it won’t post on facebook. What are possible causes of this error and how can I address it?

By the way, I am not using webview on my app. Just the widget api and a show_dialog listener in my Facebook class.

12 Answers 12

The error has been documented on the Mac Developer Library(iOS docs)

The concerned segment from the documentation will be:

URL Loading System Error Codes

These values are returned as the error code property of an NSError object with the domain “NSURLErrorDomain”.

As you can see; -999 is caused by ErrorCancelled . This means: another request is made before the previous request is completed.

Just wanted to add here, when receiving a -999 «cancelled» the problem usually is one of two things:

  • You’re executing the exact same request again.
  • You’re maintaining a weak reference to your manager object that gets deallocated prematurely. (Create strong reference)

hjpotter92 is absolutely right, I just want to provide solution for my case. Hopefully it is useful for you as well. Here is my situation:

On log in page > press log in > pop up loading dialog > call log in service > dismiss dialog > push another screen > call another service —> cause error -999

To fix it, I put a delay between dismissing dialog and pushing new screen:

It is strange that this issue happens on iOS 7 only.

I have faced the same error with Alamofire and it was because the certificate pinning. The certificate wasn’t valid anymore, so I had to remove it and add the new one. Hope it helps.

I didn’t use Corona SDK’s Facebook API but I encountered this problem when using Alamofire, the secondRequest always cancel in execution with the error -999, according to the posts I found on internet, the reason is that session property is deinit before completion of async work since it is out of the scope, I finally solved this problem by deinit the session property manually so the compiler won’t deinit it at wrong position:

In addition to what Ramon wrote, there is a third possible reason when receiving a NSURLErrorDomain -999 cancelled :

You cancelled the task while it was executing either by calling .cancel() on the datatask object or because you used .invalidateAndCancel() on the session object. If you are creating a custom session with a delegate, you should call .invalidateAndCancel() or .finishTasksAndInvalidate() to resolve the strong reference between the session and its delegate, as mentioned in the Apple Developer Documentation:

The session object keeps a strong reference to the delegate until your app exits or explicitly invalidates the session. If you don’t invalidate the session, your app leaks memory until it exits.

If you are wondering about this logging behaviour, I found the following explanation in the Apple Developer forums:

By way of explanation, back in iOS 10 we introduced a new logging system-wide logging architecture (watch WWDC 2016 Session 721 Unified Logging and Activity Tracing for the details) and lots of subsystem, including CFNetwork, are in the process of moving over to that. Until that move is fully finished you’re going to encounter some weird edge cases like this one.

Источник

NSURLErrorDomain error -999

I am using UIWebView to render a GPS map on the iPhone. When I load it with the following code:

[myWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:[textField text]]]];

I get an NSURLErrorDomain error -999. The same code works fine with other URLs like www.apple.com and www.intel.com. It doesnt seem to be a redirect issue; I tested it by creating a tinyurl for www.apple.com and it worked fine with my code. Where would I find the documentation for error code -999 or how to fix the error?

Posted on Sep 25, 2008 10:18 AM

Loading page content

Page content loaded

Error -999 can be safely ignored in a UIWebView

This is a dirty workaround that makes UIWebView work as it should

I’m still not sure what causes the error, but it might have something to do with iFrames or JavaScript requests. It’s definitely not a redirect issue.

Like JavaJini, I put a similar code in the IBAction of a button.

The first time a click on the button, it is working fine, and the second time it is not.
Maybe something has to be done before calling loadRequest a second time.

The workaround proposed by Pumbaa do not display the error, but the page is still not reloading (the error still happend).

NSURLErrorDomain error -999 == NSURLErrorCancelled.

«Returned when an asynchronous load is canceled. A Web Kit framework
delegate will receive this error when it performs a cancel operation on a
loading resource. Note that an NSURLConnection or NSURLDownload delegate
will not receive this error if the download is canceled.»

So the conjecture from pumba is correct, you do not need to display it.

The code I have given before trigger a such Error because I did a loadRequest and a reload (the reload line is not necessary).
—> making a stopLoading before the new request is a good idea.

A other way to trigger such errors is to click very quickly on 2 links. The first request is canceled (—> Trigger the -999 error).

If you want to avoid such error, you can add some overhead code in order to assure that when something is loading nothing else can be loaded. But as pumba said it is not a big deal.

Источник

Устраняем предупреждения в админ панели NextCloud

В предыдущей статье я писал как можно установить и настроить nextcloud на операционной системе Ubuntu Server 20.04 с web-сервером nginx+php-fpm и базой данных postgresql. Почитать можно тут.

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

Индексирование файлов

Для устранения запустим команды для ускорения индексирования файлов. В терминале набираем:

Включаем режим обслуживания:

И вводим данные строки:

Выключаем режим обслуживания

После данной манипуляции ошибка должна исчезнуть.

Предупреждения о текущей конфигурации /.well-known/.

  • Веб-сервер не настроен должным образом для разрешения «/.well-known/webfinger».
  • Веб-сервер не настроен должным образом для разрешения «/.well-known/nodeinfo».
  • Веб-сервер не настроен должным образом для разрешения «/.well-known/caldav».
  • Веб-сервер не настроен должным образом для разрешения «/.well-known/carddav».

Чтобы исправить данные предупреждения в конфигурационный файл nginx вашего облака внесем следующую location:

Адрес https://mynextcloud.ru измените на свой.

Также внесём следующие строки в файл .htaccess

Зависание входа в панель NextCloud

Включил https на web сервере для nextclou и появился неприятный глюк: в google chrome, opera и яндекс браузере, а также в firefox, IE и edge при входе в аккаунт и выходе из него браузер «зависает» на странице входа, но при этом авторизуется. Если нажать F5, то окажемся в своем аккаунте.
Как же победить данную проблему?

Лечится добавлением в конфигурационный файл NexCloud:

Не настроена система кэширования.

Не настроена система кэширования. Для увеличения производительности сервера, по возможности, настройте memcache.

Хочу использовать Memcached. Для этого надо установите модуль для PHP и сам memcached.

Как оказалось есть два похожих пакета:

  • php-memcache — модуль Memcache для PHP,
  • php-memcached — расширение PHP для взаимодействия с memcached.

Нужен с буквой d в конце.

настройки в /etc/php/8.0/mods-available/memcached.ini оставляю все без изменений.
В выводе phpinfo(); появился блок с описанием memcached.

Настройки запуска сервиса в /etc/systemd/system/multi-user.target.wants/memcached.service и конфигурационный файл /etc/memcached.conf тоже не менял.

Проверяем запустился ли сервис

Должно выдать что-то вроде этого

Теперь в конфиге NextCloud добавим строки:

Модуль php-imagick не поддерживает SVG

Для устранения данного предупреждения необходимо установить модуль imagick:

Не указан регион размещения этого сервера Nextcloud

Не указан регион размещения этого сервера Nextcloud, что требуется для возможности проверки номеров телефонов без указания кода страны.

Чтобы разрешить пользователям сервера указывать номера телефонов без указания кода страны, добавьте параметр «default_phone_region» с соответствующим кодом страны в соответствии с ISO 3166-1↗.

Для устранения данного предупреждения откроем конфигурационный файл NextCloud :

и добавим следующие строки:

Для устранения данных ошибок в терминале набираем следующее:

И заполняем данным текстом:

Сохраняем файл (ctrl+o, ctrl+x). И перезагружаем nginx

Заголовок HTTP «Strict-Transport-Security»

Для устранения данного предупреждения отредактируем файл Nginx headers.conf:

Добавим следующие строки:

PHP не настроен для системного окружения.

PHP не настроен правильно для получения переменных системного окружения.

Запрос getenv(«PATH») возвращает пустые результаты.
Обратитесь к разделу о конфигурации PHP и примечаниям к конфигурации PHP из руководства по установке. Обратите внимание на настройку параметров PHP, особенно при использовании механизма php-fpm.

Когда вы используете php-fpm, системные переменные среды, такие как PATH, TMP или другие, не заполняются автоматически так же, как при использовании php-cli. Вызов функции PHP, такой как getenv(‘PATH’); может возвращать пустой результат. Поэтому вам может потребоваться вручную настроить переменные среды в файле конфигурации php-fpm.

И сними с них комментарий (;).

Далее перезапустим php8.0-fpm

Значение PHP ниже рекомендуемого значения .

Разрешённое максимальное значение использования памяти PHP ниже рекомендуемого значения в 512 МБ.

В терминале набираем:

Находим и редактируем следующие строки:

Не скачиваются файлы больше 1Гб

При попытках скачать из облака файлы объемом более 1гб скачивание прерывается при достижении 1гб. Такое происходит при условии использования Nginx как реверс-прокси. Решается очень просто, нужно добавить в конфигурационный файл сайта опцию «proxy_buffering off». Открываем и добавляем эту опцию:

Если есть вопросы, то пишем в комментариях.

Также можете вступить в Телеграм канал, ВКонтакте или подписаться на Twitter. Ссылки в шапке страницы.
Заранее всем спасибо.

Если вы нашли ошибку, пожалуйста, выделите фрагмент текста и нажмите Ctrl+Enter.

Решаем проблему с ошибкой W: mdadm. Имеется сервер работающий на Ubuntu Server 16.04, после обновления системы в логах, да и Читать

NextCloud на Ubuntu Server в журнале первого выходила постоянная Ошибка «PHP Startup: Unable to load dynamic library ‘xmlrpc.so’ «

Если при работе в Linux вы получаете ошибку «getcwd() failed: No such file or directory» при запуске какого-либо скрипта или Читать

Источник

Я пытался использовать 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

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Ошибка office 16 click to run extensibility component
  • Ошибка nsis error что делать
  • Ошибка off by one
  • Ошибка np 38551 2 ps4 как исправить
  • Ошибка ods9013e odis

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии