How to

How to access native iOS functionality from JavaScript


Many of you iOS developers may have come across the need to render HTML within your native iOS app, at some point in your mobile app development career. In such cases, have you ever found it necessary to call and execute certain native functions from within your embedded HTML code? For example, how does one print the screen’s contents whilst in an HTML Web View? We came across just such a business requirement recently, and thought it worthwhile to share how we solved this problem.

Before we step into the code, let me first provide some business context around our particular implementation scenario. Our top-level business requirement was to display various types of content like pictures, videos, slide presentations and so forth in a native iOS app. However, one particular content type to be displayed was a “dynamic web content module” –  that is a package of HTML, CSS, and complex JavaScript functions. The exact problem was that these HTML modules had to communicate with the native application and vice versa, whilst running on a Web View. Coding this requirement is not as simple as invoking a method in JavaScript from HTML. The JS-API Bridge allows the module and the native application to communicate with each other. The JS-API bridge works based on the following 2 functionalities provided by the UIWebView in iOS.

shouldStartLoadWithRequest method of the UIWebView delegate
This method of the UIWebView delegate gets called each time the UIWebView loads a new URL. We can use this method to send data from JavaScript running on the web view to our native code. We can make a web request from JavaScript with a custom nonstandard protocol identifier followed with the payload (e.g. nativecall://<native call payload>). We can look for our protocol identifier and extract the data within the shouldStartLoadWithRequest method and return NO to cancel the request.

The stringByEvaluatingJavaScriptFromString method of the UIWebView enables us to evaluate a JavaScript string in the context of the currently loaded document in the web view. We can use this method to send data from the native code to JavaScript.
A working sample is available at: