In ios development, javascript calls the oc Code directly instead of modifying the url callback method.

Source: Internet
Author: User

In ios development, javascript calls the oc Code directly instead of modifying the url callback method.

In the previous ios project, you must use UIWebview to open a static page and

Call the relevant object-c code.

 

I. Previous methods for calling object-c using js

I have searched for a long time on how to use javascript to call functions and methods in object-c.

All the methods on the Internet basically specify a direction, that is, in the js Code loaded in UIWebview

By changing document. locations = "" and then calling back

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

Function. In the above function, NSURLRequest is intercepted to parse the parameters passed in js, and then

To select a method that has already been defined.

Is there any other way? I have been searching for a few months! But there is a transfer.

 

I happened to know the javascriptCore. framework library.

So things have a turning point.

 

Ii. directly call the oc method in js

 

Now let's look at how to call the oc method in javascript of UIWebView.

 

 

First, create a UIWebView. The Code is as follows:

//// Webview. m // login // Created by wangdan on 15-3-19. // Copyright (c) 2015 wangdan. all rights reserved. // # import "webview. h "# import
 
  
@ Implementation webview-(id) initWithFrame :( CGRect) frame {self = [super initWithFrame: frame]; if (self) {self. webview = [[UIWebView alloc] initWithFrame: CGRectMake (0,310, self. bounds. size. width, 300)]; self. webview. backgroundColor = [UIColor lightGrayColor]; NSString * htmlPath = [[NSBundle mainBundle] resourcePath]; htmlPath = [htmlPath stringByAppendingPathComponent: @ "html/index.html"]; NSURL * localURL = [[NSURL alloc] initFileURLWithPath: htmlPath]; [self. webview loadRequest: [NSURLRequest requestWithURL: localURL]; [self addSubview: self. webview]; JSContext * context = [self. webview valueForKeyPath: @ "documentView. webView. mainFrame. javaScriptContext "]; context [@" log "] = ^ () {NSLog (@" ++ Begin Log ++ "); NSArray * args = [JSContext currentArguments]; for (JSValue * jsVal in args) {NSLog (@ "% @", jsVal);} JSValue * this = [JSContext currentThis]; NSLog (@ "this: % @", this); NSLog (@ "------- End Log -------") ;}; // [context evaluateScript: @ "log ('ider ', [7, 21], {hello: 'World', js: 100}); "] ;}return self ;}@ end
 

 

(1) In the above Code, use javascriptCore. framework, first use UIWebview to load a static webpage, and

Use

JSContext * context = [self. webview valueForKeyPath: @ "documentView. webView. mainFrame. javaScriptContext"];

Obtain the javascript execution environment of the UIWebview.

 

 

(2) define a js function in the javascript execution environment. Pay attention to the key points.

 

The execution body of this function is completely written in objective-c code, that is, the following:

    context[@"jakilllog"] = ^() {            NSLog(@"Begin Log");            NSArray *args = [JSContext currentArguments];            for (JSValue *jsVal in args) {                NSLog(@"%@", jsVal);            }            JSValue *this = [JSContext currentThis];            NSLog(@"-------End Log-------");        };
 
 

(3) imagine, in the defined webview, if we use js to execute the log function, will we call the block code in the above oc? The answer is yes!

Next, let's take a look at how the html and js Code loaded in UIWebView are written.

(4)index.html code

 

 
 
<Script type = "text/javascript" src = "index. js"> </script> Click button
 
The preceding html defines a button and then references index. js. The response function of clicking the button is buttonClick ()
This function is defined in index. js as follows:
function buttonClick(){jakilllog("hello world");}

 

Click this button to call the jakilllog () function. The jakilllog () function is obviously a block Segment implemented in oc,

It is the block Segment of the green part.

 

Will it be executed by clicking the button? The answer is yes.

Below

 

Is the result of execution



Click the button in html to execute the code in oc.

It indicates that the intention of calling oc directly from js is achieved.

 

 

 

 

 

 

 

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.