iOS development, JavaScript calls the OC code directly instead of changing the URL callback method

Source: Internet
Author: User

In a previous iOS project, you would need to open a static page via UIWebView and in a static page

Call the relevant OBJECT-C code.

first, the method of using JS to call Object-c

about how to call the functions and methods in Object-c using javascript, I searched for a long time

All the methods on the net, basically pointed out a direction, that is in the UIWebView loaded in the JS code

By changing the document.locations= "" and then callback the UIWebView

-(BOOL) WebView: (UIWebView *) WebView shouldstartloadwithrequest: (nsurlrequest *) Request Navigationtype: ( Uiwebviewnavigationtype) Navigationtype

function, in the above function, by intercepting Nsurlrequest parse the parameters passed in JS, and then according to the parameters

To choose a method that has already been defined.

Is there any other way? I've been looking for a few months and I haven't found it! But there was a turnaround.

I happen to know javascriptcore.framework this library.

So things got a turn.

Second, the method of calling OC directly in JS

Not much nonsense to say, now look at how to call OC in the UIWebView JavaScript method

First, create a uiwebview with the following code:

webview.m//login////Created by Wangdan on 15-3-19.//Copyright (c) 2015 Wangdan. All rights reserved.//#import "Webview.h" #import <JavaScriptCore/JavaScriptCore.h> @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, +], {hello: ' World ', js:100}); return self;} @end

(1) in the above code, using Javascriptcore.framework, first load a static web page with UIWebView, and

Use

Jscontext *context = [Self.webview valueforkeypath:@ "DocumentView.webView.mainFrame.javaScriptContext"];

Gets the JavaScript execution environment for the UIWebView.

(2) In the JavaScript execution environment, define a JS function, pay attention to the key points

The executing body of this function is written entirely in Objective-c code, which 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 definition of WebView, if you use JS to execute log this function, then will not invoke the above OC Block code, the answer is YES!

Let's see how the HTML and its JS code are written in UIWebView.

(4) Index.html code

<!--//  Created by Wangdan on 15-3-19.--><!--//  Copyright (c) 2014 Wangdan. All Rights reserved.--><! DOCTYPE html>

The above HTML defines a button and then references Index.js, and clicking on the button's response function is ButtonClick ()
The function is defined in Index.js, as follows
function ButtonClick () {jakilllog ("Hello World");}

This means that by clicking on the button, the Jakilllog () function is called, and the Jakilllog () function is clearly a block segment we implemented in OC,

is the block segment of the green section above.

Do you click button to execute? The answer is yes.

Below

Is the result of the execution



Click the button in the HTML to execute the code in OC

Describes the intention of calling OC directly from JS to achieve.

iOS development, JavaScript calls the OC code directly instead of changing the URL callback method

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.