Interaction between js (javascript) and OC (Objective-C), ocobjective-c

Source: Internet
Author: User

Interaction between js (javascript) and OC (Objective-C), ocobjective-c

In essence, communication between oc and js is to send messages, that is, function calls. iOS7 will officially announce the convenient call between them in JavaScriptCore framework. Previously, we had to use the UIWebViewDelegate protocol of UIWebView.

1
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType;

Or

1
- (void)webViewDidStartLoad:(UIWebView *)webView;
 
 
  • Oc-> js stringByEvaluatingJavaScriptFromString. The parameter is an NSString whose content is JavaScript code (this can be a js function, a js Code, or a combination of them ), if a js function has a return value or a js Code has a return value, you can obtain it through the return value of stringByEvaluatingJavaScriptFromString.
  • Js-> oc uses the redirection principle of webView (that is, specify document again in js. location value, which is a url), you only need to specify the functions and parameters in the oc to be called according to custom rules in the url string, and then capture and process the request through the shouldStartLoadWithRequest function in the OC.
One JS calls OC

Js calls to iOS are divided into two situations

Directly call the method in js

Calling methods through objects in js

Directly call the method in js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
-(Void) webViewDidStartLoad :( UIWebView *) webView {

// Create a JSContext object (jscontext is obtained through the current webView key)
JSContext * context = [webView valueForKeyPath: @ "documentView. webView. mainFrame. javaScriptContext"];
// GetCurrentUser is the js method name, and is assigned to a block with the iOS code
Context [@ "getCurrentUser"] = ^ (){
// Write the OC code in the block
Return [[NSUserDefaults standardUserDefaults] objectForKey: @ "MYJSANDOC"];
};
Context [@ "encodeParam"] = ^ (){
NSArray * args = [JSContext currentArguments];
NSString * param = [NSString stringWithFormat: @ "% @", args [0];
NSString * result = [[[YXBaseRequestManager alloc] init] encryptUseAES: param key: @ "1% 7jhs # Zjasd & tr *"];
Return result;
};

}
Calling methods through objects in js

In this method, we need to useJSExport
JSExportIt is a protocol. After the custom protocol, the declared variables in it will be open to JS, and we can call it.

First, we need to customize a protocol to add header files.#import <JavaScriptCore/JavaScriptCore.h>, Inherited fromNSObject

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
  
# Import <Foundation/Foundation. h>
# Import <JavaScriptCore/JavaScriptCore. h>

// First create a protocol that implements the JSExport Protocol
@ Protocol JSObjectText <JSExport>

// Here we test several parameters
-(Void) JSObjectTextPush;

@ End

// Let the class we created implement the above Protocol
@ Interface JSObject: NSObject <JSObjectText>

@ End

Implemented in. m

1
2
3
4
5
6
7
8
9
10
11
# Import "JSObjectText. h"

@ Implementation JSObjectText

// Store the local Key. After the call, check whether the key exists and whether the native method is used.
-(Void) JSObjectTextPush
{
[[NSUserDefaults standardUserDefaults] objectForKey: @ "MYJSANDOC"];
}

@ End

Call

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
-(Void) webViewDidFinishLoad :( UIWebView *) webView
{
// Call this method after the webpage is loaded

// Create a JSContext object (jscontext is obtained through the current webView key)
JSContext * context = [webView valueForKeyPath: @ "documentView. webView. mainFrame. javaScriptContext"];

// In the second case, js is called through an object. Assume that there is an object testobject in js that is calling the method.
// First create the object of the new class and assign it to the js object

JSObjectText * text = [JSObjectText new];
Context [@ "testobject"] = text;

// Similarly, we used the method we just used to simulate the js call method.
NSString * jsStr = @ "testobject. JSObjectTextPush ()";
[Context evaluateScript: jsStr];


}
2 OC calls JS

The method is simple. After loading webview, you can call it by clicking an event or returning a value.stringByEvaluatingJavaScriptFromStringTo call JS Code.

1
2
3
4
5
6
7
8
9
10
/*
* Click Event
* Call the javaScript method postStr () and obtain the return value.
* Output the return value to the console.
*/
-(Void) ocFromJs :( id) sender
{
NSString * str = [self. webview stringByEvaluatingJavaScriptFromString: @ "postStr ();"];
NSLog (@ "JS return value: % @", str );
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.