decodeURIComponent not unescape if you're using unicode in JavaScript…

… and used stringByAddingPercentEscapesUsingEncoding from Cocoa.

If you're communicating between Cocoa and JavaScript in your iPhone application (I guess we call 'em hybrid apps these days 'cos it sounds cool), you may have to pass unicode content back and forth (e.g., as the argument to a function call in JavaScript).

On the Cocoa side of things, it's as easy as:

NSString *js = [NSString stringWithFormat:@"myLovelyJavaScriptFunction(\"%@\");", [someContent stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    [myBeautifulWebView stringByEvaluatingJavaScriptFromString:js];

On the JavaScript side, you may be tempted to use unescape on the argument. Don't or you won't get any of the Unicode goodness in your string (and we all know that healthy strings needs lots and lots of Unicode!) Instead use decodeURIComponent like this:

function myLovelyJavaScriptFunction(myAwesomeParameter) {
  var myRidiculouslyFabUnescapedContent = decodeURIComponent(myAwesomeParameter);
  ("Unicode radness follows: " + myRidiculouslyFabUnescapedContent);
}

Hope this helps someone else out there :)

Comments