UIWebView: Why does the request not time out when using a non-existant hostname?

我怕爱的太早我们不能终老 提交于 2019-12-10 11:24:39

问题


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:

  1. webView: shouldStartLoadWithRequest: navigationType:
    • (returns true always for testing)
  2. 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:

  1. Is it correct for webViewDidStartLoad to be called on an invalid URL?
  2. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!