iOS Dev Nugget 120 Running JavaScript on UIWebView and WKWebView


Need to run a code review on your codebase? Hire me

Prior to iOS 8, if you wanted to run JavaScript on a UIWebView and process the results in native code (ObjC, Swift, etc), you'd have to use -stringByEvaluatingJavaScriptFromString: doing the following:

NSString* resultAsAString = [webView stringByEvaluatingJavaScriptFromString:@"
    //1. Process
    //2. Serialize into string
    //3. return string
//4. Convert resultAsAString from NSString into native objects (NSArray, NSDictionary, NSString int, etc)
//5. Finally process

You needed to do your own serializing into string in JavaScript and then unserialize it again in native code, converting the data into native objects!

With iOS 8, however, you can use WKWebView and do this:

[webView evaluateJavaScript:@"
    //1. Process
    //2. Return results in JavaScript primitives
" completionHandler:^{
    //3. Process (the results are automatically converted into NSArray, NSDictionary, NSString, int, etc already)

WKWebView automatically does the type conversion for you and the JavaScript evaluation is asynchronous.

There's a lot more to WKWebView than performance improvements. A good way to start is to check out WKUserScript and how you can attach your own JavaScript at document load start and end time to customize the page you are loading.

Your feedback is valuable: Do you want more nuggets like this?   Yes   or   No


Like this and want such iOS dev nuggets to be emailed to you, weekly?

Sign Me Up! or follow @iosdevnuggets on Twitter


View archives of past issues