In iOS, how can I call an Objective-C method from Javascript in a UIWebView and have it send data back to the Javascript? I know that this could be done on OS X using the Webkit library, but is this possible on iOS? How does PhoneGap achieve this?
In iOS, how can I call an Objective-C method from Javascript in a UIWebView
Share
There is an API to call JavaScript directly from Objective-C, but you cannot call Objective-C directly from Javascript.
How to tell your Objective-C code to do something from the Javascript in your WebView
You have to serialize your Javascript action into a special URL and intercept that URL in the UIWebView’s delegate’s
shouldStartLoadWithRequestmethod.There you can deserialize that special URL and interpret it to do what you want on the Objective-C side. (You should return
NOin the aboveshouldStartLoadWithRequestmethod so the UIWebView doesn’t use your bogus URL to actually make an HTTP request to load a webpage.)How to Run Javascript Code from Objective-C
Then you can run Javascript from Objective-C by calling this method on your webview.
Example Code
I recommend using a bogus URL scheme so it will be easy to tell the difference between your action URLs and legit requests. You can make this request in the Javascript along these lines:
Then in the
UIWebView.delegate‘sshouldStartLoadWithRequestmethod, you can inspect the URL scheme and fragment to check if it’s a normal request or one of your special actions. (The fragment of a URL is what comes after the#.)(Read this answer if you need help deserializing your json string into an NSDictionary.)