General Overview:
In essence, the communication interaction between OC and JS is to send a message, that is, a function call, as long as the process of interaction correctly specifies that the other party needs to call the function and parameters are OK
Oc-->js Stringbyevaluatingjavascriptfromstring, whose argument is a nsstring string content is the JS code (this can be a JS function, a JS code or their combination), When the JS function has a return value or a JS code has a value return can be obtained by stringbyevaluatingjavascriptfromstring return value
Js-->oc Using the WebView redirection principle (that is, to re-specify the value of Document.location in JS, this is a URL), as long as the custom rules in this URL string to specify the required functions and parameters in OC, and then through the OC in the Shouldstartloadwithreque St function to capture processing requests, processing end, if JS also want to get some return parameters, also let OC go through stringbyevaluatingjavascriptfromstring call just JS pass the callback JS function on the line, by the parameter also passed, Perfect!!!
UIWebView is the control that renders the mesh in the iOS SDK, and when the page is displayed, we can hack the page and display what we want to display. There is a need to use JavaScript knowledge, and the way UIWebView interacts with JavaScript is stringbyevaluatingjavascriptfromstring:
With this approach we can invoke JavaScript via OBJC and inject JavaScript.
First, let's take a look at how to invoke JavaScript:
- [WebView stringbyevaluatingjavascriptfromstring: @ "myFunction ();"];
Note: stringbyevaluatingjavascriptfromstring This method has a place to pay attention, not a bug, but there are problems, you need to pay attention!
If the stringbyevaluatingjavascriptfromstring executes a JS function with parameters, this parameter inside if with (\ r \ n ') and so on, JS there is no such value, the need to escape these bands, such as the following to write JS to receive the complete message
message = [Message stringbyreplacingoccurrencesofstring:@ "\ n" withstring:@ "\\\\n"];
NSString *jsmethod = [NSString stringwithformat:@ "Jsmethod ("%@ ")", message];
There is also a place where these 2 kinds of writing appear to be the same, essentially different, if the use of ' quotes, if the message with ', messages will not pass! So it's best to use "
NSString *jsmethod = [NSString stringwithformat:@ "Jsmethod ("%@ ")", message];
NSString *jsmethod = [NSString stringwithformat:@ "Jsmethod ('%@ ')", message];
Here MyFunction () is our JavaScript method.
To see what to inject into JavaScript, let's start by writing a JavaScript that needs to be injected:
- function Showalert () {
- Alert (' In Show alert ');
- }
Save As Test.js, and then drag to the resource group under Xcode. Then use the code to inject this JS (as in the Viewdidload method) when initializing.
- NSString *filepath = [[NSBundle mainbundle] pathforresource:@ "test" oftype:@ "JS"];
- NSString *jsstring = [[NSString alloc] initwithcontentsoffile:filepath];
- [WebView stringbyevaluatingjavascriptfromstring:jsstring];
This will inject the above JS, then we can call the JS method at any time, how to invoke, the above is introduced.
Then we can use JS to invoke the OBJC method. Of course, the principle is to use UIWebView Redirect request , use shouldstartloadwithrequest can capture to UIWebView all requests! If we send a specific request in JS, it contains the OC function and the request parameter that will be called.
First we write a JavaScript method as follows:
- function SendCommand (cmd,param) {
- var url= "TestApp:" +cmd+ ":" +param;
- document.location = URL;
- }
- function Clicklink () {
- SendCommand ("alert", "How are You?") ");
- }
TestApp is a protocol of its own definition, as long as not and HTTP, HTTPS and other international general protocol header conflict can be, the name casually take;
CMD is the method of OC to be called;
Param is the parameter of the call
Then use Document.location to achieve the goal! The above "testapp://" +cmd+ ":" +param is a custom request format that you can change, such as the following
Document.location= "Mycustomprotocolname:functionname?param1=value1¶m2=value2 ...".
JS inside how to define all can, how convenient how to come! However, after capturing this request in the Shouldstartloadwithrequest method, you have to correspond to the resolution, judge is not your own specific request!
Then call this JS method in your HTML, such as:
- "Button" value= "click me!" onclick= "Clicklink ()"/>
- JS file inside if the Chinese. To use JS inside the method encodeURI to deal with. Otherwise, Xcode uses
nsstring* rurl=[[[request URL] absolutestring]stringbyreplacingpercentescapesusingencoding:nsutf8stringencoding]; Unable to get Chinese
var url= "protocol://" +encodeuri ($ ("#textarea"). Val ());
The URL contains Chinese, garbled characters appear in Chinese (in OC Code)
When it's transmitted, it's written.
NSString *ratecardsname_cn=[[nsstring stringwithformat:@ "%@", Ratecardsname] Stringbyaddingpercentescapesusingencoding:nsutf8stringencoding];
Write it when you get it.
NSString *URLSTR = [[Request]. URL absolutestring]stringbyreplacingpercentescapesusingencoding:nsutf8stringencoding];
Finally we intercept this redirect request in Uiwebvew:
- #pragma mark--
- #pragma Mark Uiwebviewdelegate
- -(BOOL) WebView: (UIWebView *) WebView shouldstartloadwithrequest: (nsurlrequest *) Request Navigationtype: ( Uiwebviewnavigationtype) Navigationtype {
- NSString *requeststring = [[Request URL] Absolutestring]stringbyreplacingpercentescapesusingencoding: Nsutf8stringencoding];
- if ([Rurl hasprefix:@ "testapp://"]) {
- If the protocol is defined by itself, then the methods and parameters in the protocol are intercepted and the OC method is called manually here after the error is determined.
- }
- return YES;
- }
See the code is not clear enough to understand it? I think PhoneGap may have done so, not studied. But there is an open source project that you can look at, which allows JavaScript to invoke the Objective_c method. Call Jsbridge-to-cocoa.
http://code.google.com/p/jsbridge-to-cocoa/
There are two other related projects
Webviewjavascriptbridge and Gajavascript are worth studying slowly.
Source: http://blog.csdn.net/favormm/article/details/6603923
UIWebView interaction with JavaScript