Say, I have an address bar which is a UITextField called textField, and a UIWebView named webView. Most of the time the follow code works:
[webView loadURL:[NSURL URLWithString:textField.text]];
When I put in some long string with special characters, URLWithString:
simply returns null
. The Readability bookmarklet is a good example:
javascript:(function(){readConvertLinksToFootnotes=true;readStyle='style-newspaper';readSize='size-medium';readMargin='margin-wide';_readability_script=document.createElement('script');_readability_script.type='text/javascript';_readability_script.src='http://lab.arc90.com/experiments/readability/js/readability.js?x='+(Math.random());document.documentElement.appendChild(_readability_script);_readability_css=document.createElement('link');_readability_css.rel='stylesheet';_readability_css.href='http://lab.arc90.com/experiments/readability/css/readability.css';_readability_css.type='text/css';_readability_css.media='all';document.documentElement.appendChild(_readability_css);_readability_print_css=document.createElement('link');_readability_print_css.rel='stylesheet';_readability_print_css.href='http://lab.arc90.com/experiments/readability/css/readability-print.css';_readability_print_css.media='print';_readability_print_css.type='text/css';document.getElementsByTagName('head')[0].appendChild(_readability_print_css);})();
According to this answer, I can use stringByAddingPercentEscapesUsingEncoding
to escape the string, and indeed it works fine for this case.
My question is: Is this safe to always call stringByAddingPercentEscapesUsingEncoding:
before passing the string to the webView? Does the following have any consequences?
[webView loadURL:[NSURL URLWithString:[textField.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]]
Thanks!
EDIT: What I mean by 'safe' is that while this works with URLs containing Unicode characters, does it still work fine with 'normal' URLs?
EDIT 2: If this is 'safe', why isn't it the default behaviour?
Since there's no other answers to my question, I decided to use the following - (NSURL *)URLValue
method instead of - (NSURL *)URLWithString:
as a safe measure:
- (NSURL *)URLValue {
NSURL *URL = [NSURL URLWithString:self];
if (URL) return URL;
return [NSURL URLWithString:[self stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
}