IOS JS interaction uses the system JSContext to call the OC method and Objective-C to call the JavaScript method. javascript interacts with oc.
Ios js interaction is divided into two parts: 1. oc calls js
This implementation is relatively simple,
The local html, js, and css files are loaded in my project. Note that when you drag these files into the project, you choose to copy them to the project, (The dragged folder is blue with a relative path). Otherwise, the path of css and js may be faulty.
Load local html:
Oc calls js: Get a piece of code
2. js calls oc. js calls oc in two ways: 1. js side directly calls the Method
Here we will talk about a new api called JavaScriptCore launched by ios7. First we introduce this class and initialize a JSContext object.
In the webViewDidFinishLoad method
Jscontext is obtained through the current webView key.
Establish a bridge between our context object and the js method,
2. js end call methods through objects
When it comes to object calling methods, we must first have an object. Therefore, we must first create a js interaction class and declare and implement the corresponding interaction method, note that we need to import the JavaScriptCore framework in this custom interaction class and declare a protocol that complies with the JSExport protocol (a bit round, see the figure ), declare our interaction method in this Protocol, and finally let our interaction class comply with our custom protocol
Implement corresponding js interaction methods in. m of the Interaction Class and implement the operations we want
Notice
JSExportAs (invoke,-(void) invoke :( NSString *) method args :( NSString *) args );
This method does not work. The function of this method is to make-(void) invoke :( NSString *) method args :( NSString *) when the js-side method has two or more parameters *) args; this method replaces the corresponding js method, because the method name on the oc side must be consistent with that on the js side, otherwise it will not be called.
Finally, initialize our interaction object in our webViewDidFinishLoad method, and let the context establish a connection with it. OK.
HybridApi calls this method -->
3. The code for Objective-C to call JavaScript is as follows:
[Self. webView evaluateJavaScript: [NSString stringWithFormat: @ "_ YutaAppOnPrepare ()"]
CompletionHandler: ^ (id response, NSError * error)
{
}];