问题
My situation is this:
- I have a
UIWebView
which makes a POST request to a URL where the hostname is provided by the user. - When the hostname does not exist, I need to timeout so that I can alert the user to say that they should check the their settings.
What is happening:
I make a request like this:
NSString *theURL = [NSString stringWithFormat:@"https://%@%@", _hostname, LOGIN_PART_URL];
NSString *body = [NSString stringWithFormat:@"Username=%@&Password=%@", _username, _password];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:theURL]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:_timeoutInSecs];
[request setHTTPMethod: @"POST"];
[request setHTTPBody: [body dataUsingEncoding: NSUTF8StringEncoding]];
[web loadRequest:request];
When the hostname does not exist on the network, I do not get any timeout response.
I have implemented all delegate methods of UIWebViewDelegate
, and I get the following called in order when I use a non-existent hostname:
webView: shouldStartLoadWithRequest: navigationType:
- (returns true always for testing)
webViewDidStartLoad
And that's it - nothing after that.
I'm surprised that webViewDidStartLoad
gets called, as this would suggest that it found the URL and thinks it can get data back from it. But it can't as the URL does not exist!
Am I doing something wrong here?
I have a workaround which I am going to implement, which uses an NSTimer
to see if a response has been received within the timeout period. However, I am having issues with cancelling a request for a UIWebView
- but that's a topic for my next SO question!
So my questions:
- Is it correct for
webViewDidStartLoad
to be called on an invalid URL? - Should I be seeing a request timeout error returned, with the way I have setup my request?
Thanks in advance!!
Stretch :)
回答1:
Use delegate method
webView:didFailLoadWithError:
Get the error from it. If the error code is
-1000 - Bad Url
-1001 - Request timed out
-1003 - Cannot find host
-1004 - Cannot connect to host
-1005 - Network connection lost
-1006 - NSLookupFailed
By checking this you can alert the user about the error.
来源:https://stackoverflow.com/questions/10628409/uiwebview-why-does-the-request-not-time-out-when-using-a-non-existant-hostname