收录日期:2021/01/22 02:41:51 时间:2010-03-31 04:43:17 标签:cocoa,url,webkit

Is there a way to visit a website without typing http://?

If you're looking to duplicate Safari's "protocol guessing" or even "TLD guessing", you'll have to implement this yourself.

From a user's perspective, you usually don't have to enter the protocol into a web browser because it's safe to assume the protocol is "http". From the developer's perspective, you'll need to specify the protocol when forming the URL.

Since you tagged this question "webkit", I'll assume you're working with a WebView. From the documentation on -[WebView setMainFrameURL:]:

This method is functionally equivalent to invoking [[webView mainFrame] loadRequest:[NSURLRequest requestWithURL: [NSURL URLWithString:URLString]]].

Note, the poorly-named -setMainFrameURL: method accepts an NSString, not an NSURL as you'd expect. So considering this, you must still provide a valid URL string in order to get a valid URL.

In the case you mentioned in your comment, however, it's important to note "http://digg.com" is as valid as "http://www.digg.com". This is handled by the target domain's name server and has nothing to do with whether the URL is valid or not. This is because "digg.com" likely still resolves to an actual host (ie the record for the domain without a host forwards to "www"). Some domains don't do this, so you may want to handle this case (invalid host name) separately by trying to prepend "www" if absent. The important thing is "valid URL != valid domain".

All this considered, you'll have to roll your own "guessing" solution.