iOS WebView加载请求时出现NSURLErrorDomain error -999错误的原因及解决方案咨询
Hey there! Let's break down that NSURLErrorDomain error -999 you're encountering in your UIWebView. It's super common and usually harmless, which explains why your API flow still completes normally.
原因分析
First, let's clarify what this error actually means: it's the NSURLErrorCancelled code, which simply indicates a network request was canceled before it finished. The most common triggers are:
- The WebView started loading one request, then immediately received a new one (e.g., a page redirect, or the user quickly tapping a link that replaces the current load). The original request gets canceled, firing this error.
- The WebView itself is being destroyed or removed from the view hierarchy (like when its parent view controller is popped) while a load is in progress.
- A sub-resource request (like an image, script, or stylesheet) on the page gets canceled, not the main page load itself.
As for why your API flow still works? Chances are the error is tied to a canceled secondary request, while the main page or critical API call already succeeded.
最优解决方案
Since this error is often benign, here are the best ways to handle it:
1. Filter out the error entirely (most recommended)
In your didFailLoadWithError delegate method, just check for the -999 code and skip any error handling for it. This prevents false positive error messages or unnecessary interruptions to your flow:
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error { // Ignore the "request canceled" error if (error.code == NSURLErrorCancelled) { return; } // Handle actual failures here (e.g., no network, invalid URL, 404) NSLog(@"Genuine WebView load error: %@", error.localizedDescription); // Add your user-facing error prompts or recovery logic here }
2. Avoid accidental duplicate requests
If the error is triggered by rapid user actions (like double-tapping links), explicitly stop the current load before starting a new one. This makes the cancellation intentional instead of accidental:
// When initiating a new request [self.webView stopLoading]; [self.webView loadRequest:yourNewRequest];
3. Sync WebView lifecycle with its parent
Prevent the error from firing when your view controller is dismissed by stopping the WebView's load and clearing the delegate in the appropriate lifecycle methods:
- (void)viewWillDisappear:(BOOL)animated { [super viewWillDisappear:animated]; [self.webView stopLoading]; } - (void)dealloc { // Clear delegate to avoid dangling references self.webView.delegate = nil; [self.webView stopLoading]; }
A quick note: This same logic applies to WKWebView too—just check for NSURLErrorCancelled in its failure delegate methods, and you'll be good to go.
内容的提问来源于stack exchange,提问作者Jitendra Yadav

