IOS JS and OC Interaction/JS and native call each other

Source: Internet
Author: User

Now more and more demand in the app is to display HTML or HTML5 content through UIWebView, JS and native OC code interaction is very common.

JS Call native OC code

The first type of mechanism

(1) Most commonly used is the use of -(BOOL) WebView: (UIWebView *) WebView shouldstartloadwithrequest: (nsurlrequest *) request Navigationtype: (uiwebviewnavigationtype) Navigationtype This UIWebView proxy method to intercept the JS sent request, if it is a contractual request, then trigger the local execution of the OC method

I encountered two common scenarios:

(1.1) During the page buffer loading process, the Shouldstartloadwithrequest: can intercept multiple requests, find the agreed keyword, lock the contract request can trigger the local OC

(1.2) The page has the focus area of the button category, click Trigger Request, through Shouldstartloadwithrequest: to judge the request, trigger local OC

Example: HTML Share button

<HTML>    <Header>        <Metahttp-equiv= "Content-type"content= "text/html; charset=utf-8" /><Scripttype= "Text/javascript">functionShareclick () {Loadurl ("ios//:shareaction");        //This link corresponds to the keyword of the same link in the following iOS methods } </Script>    </Header>    <Body>        <H2>Click on the button above WebView to trigger the local OC sharing method</H2>        <Buttontype= "button"onclick= "Shareclick ()">Button name</Button>    </Body></HTML>

-(BOOL) WebView: (UIWebView *) WebView shouldstartloadwithrequest: (Nsurlrequest *Request Navigationtype: (uiwebviewnavigationtype) navigationtype{nsstring*requesturl =request. url.absolutestring;
DLog(@"Request url:%@", Requesturl);
//judgment is a commodity
if(! [NSString Isempty:requesturl] && [Requesturl hasprefix:@ "hfmall://"] {//contract by request prefix is "hfmall://" to determine whether a product can even intercept valid parameters from the request link if it is frequently processed and several parameters or special characters, you should consider using JSON to do 64-bit spelling in the link upload come over Nsrange Range= [Requesturl rangeofstring:@ "hfmall://"]; if(Range.length >0) {NSString*shangpinid =[Requesturl substringFromIndex:range.length]; Goodsdetailviewcontroller*DETAILVC =[[Goodsdetailviewcontroller alloc] init]; detailvc.shangpin_id=Shangpinid; [Self.navigationcontroller PUSHVIEWCONTROLLER:DETAILVC Animated:yes]; return NO; //execute local code return no } }
Click the Share button on the UIWebView page to perform the local OC sharing method
//is article sharing
Nsrange Range1 = [Requesturl rangeofstring:@"ios//:shareaction"];
if (range1.length! = 0) {
[Self share];//Execute sharing method
return NO;
}
//todo: Other circumstances intercept judgment
return YES; //There is no valid need to intercept the link walk system default method
}

The second type of mechanism

Javascripcore

The framework begins to appear in iOS7, enabling the JS and native OC native interactions to be added to the header file #import <JavaScriptCore/JavaScriptCore.h>

[WebView Loadrequest:request]; Get the JS context when the request starts or the request is completed

(1) JS Free Choice timing Call native end OC code

HTML side

<HTML>    <Header>        <Metahttp-equiv= "Content-type"content= "text/html; charset=utf-8" />        < Script type = "Text/javascript" > function Secondclick () { Ioshidebottombar(' parameter 1',' reference Number 2'); recognized as red background key name in OC code }
</script>
</Header> <Body> <H2> JS Free Choice timing Call native end OC code </H2> <Buttontype= "button"onclick= "Secondclick ()"> button name </Button> </Body></HTML>

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

context[@ "Ioshidebottombar"] = ^ () { // @ "Ioshidebottombar" is the method name that is executed with the JS convention, so JS is free to select the time to invoke native side OC Code

DLog (@ "%@", [Nsthread CurrentThread]); //Print current thread

     NSArray *args = [JSContext currentArguments];//回调js 方法iosHideBottomBar传递的参数

        for (JSValue *jsVal in args) {

            DLog(@"%@", jsVal.toString);

        }

__block jscontext *contextobject = context;

Dispatch_async (Dispatch_get_main_queue (), ^{

Self.isshowlikefooter = NO;

[Self handlehiddenbottombar];

nsstring *[email protected] "xxxxx (' if a return value needs to be passed ')"; //Ready to execute JS code xxxxx callback return value by convention method

[ContextObject evaluatescript:jsstring];

});

};

The closure is the callback that gets in the non-main thread, and if you need to process the UI to update the current test environment in the main thread to the XCode 8.0 simulator 5s 8.3 Prints the result as follows

/**
2016-11-11 17:05:54.447 dailylife[4163:181210] <nsthread:0x7ff68cc2fd90>{number = 7, name = (NULL)}

(LLDB) PO [nsthread CurrentThread]

<nsthread:0x7ff68a423150>{number = 1, name = main}

**/

Section:

The two mechanisms are different:

A. The former needs to constantly filter judgment on each request that JS initiates, and then execute the already defined OC method, because it is impossible to predict the timing of the local OC method.

B. The latter JS and OC conventions the same method name do identify keyword ioshidebottombar in Jscontext get WebView js context, tell JS Local have this same method name OC method, you can call (in child thread) at any time.

Experience it and find that the latter is more reasonable for this webView control call when needed. But now a lot of third-party use is the former, blocking the method of URL judgment, such as "like" is, so we should master both methods, when needed to choose a relatively better way to deal with the implementation

Native OC Call JS

Call time is supposed to be webfinishload after

(1) stringbyevaluatingjavascriptfromstring: I use this method to get WebView title

NSString *title = [WebView stringbyevaluatingjavascriptfromstring:@ "Document.title"];

@ "Document.title" is passed to JS (JS call native) is asynchronous

When JS returns the title string (native call JS) is synchronously obtained

The stringbyevaluatingjavascriptfromstring method should be executed in the main thread,

This method can also be OC JS pass parameters to each other

This method calls the timing: should be webview after the request is completed before invoking the JS method, here to use stringbyevaluatingjavascriptfromstring, because

To wait for the page to load, the page is not loaded is equivalent to some objects do not necessarily create a successful, then JS time is easy to find the object

(2)

//Create object context get JS context Jscontext *context=[webview Valueforkeypath:@ "  DocumentView.webView.mainFrame.javaScriptContext"];      \
*jsstring=@ "ioshidebottombar(' parameter 1 ', ' parameter 2 ')"// ready to execute JS code and pass parameter 1 parameter 2[context evaluatescript:jsstring] to iOS; // Ioshidebottombar

Other information:

I have also deliberately considered the possibility of reciprocal return values

In the specific above method example, the use of the method name when the special emphasis on parameters, and the return value of the case no longer repeat

Reference:

http://blog.devtang.com/2012/03/24/talk-about-uiwebview-and-phonegap/

Http://www.jianshu.com/p/d19689e0ed83

IOS JS and OC Interaction/JS and native call each other

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.