Reprint--Invoke and transmit values (with HTML code) based on native JS and OC methods

Source: Internet
Author: User
Tags uikit

Recently, there is a product activity interface, to communicate with the Web, the user in the page click on the product ID to the client, that is, JS interaction, in fact, it is the method of mutual call.

This article describes how to perform native JavaScript interactions

This article includes JS call oc method and pass value, OC Call JS method and pass value

Originally wanted to put HTML into the server, and then access, but think if the HTML in the local loading more helpful to understand, put HTML into the project

HTML code
<! DOCTYPE html><Html><Head><Metacharset="UTF-8" ></Head><Body><Divstyle="margin-top:20px" ><H2>js and OC Interaction</H2><InputType="Button"Value=Invoke local method (call)onclick="Tianbai.call ()" ></Div><Div><InputType="Button"Value="Evoke Getcall: (NSString *) callstring Pass Value"onclick="Call ()" ></Div><Script>var call =function ( var callinfo = json.stringify ({ "Jianshu": " Http://www.jianshu.com/users/55c8fdc3c6e7/latest_articles "}); Tianbai.getcall (callinfo);} var Callback = function (str) {alert (str);} var alercallback = function ( Span class= "Hljs-params") {alert (</script></ body></HTML>    

The code for the above HTML: two buttons created

The first button binds the tianbai.call() method, and here tianbai is an object that is described in the following OC code to invoke the tianbai.call() method on behalf of the tianbai object call()

The second button binds a method that call() calls the method in the following JavaScript, which, call() in JavaScript, call() defines a callInfo parameter that tianbai.getCall(callInfo) represents the tianbai object caller getCall in the method. The callInfo following two methods are used by OC to invoke the JavaScript method, where callback returns Str,alercallback as OC only calls the JavaScript Method!

OC Code

Demo using native JavaScriptCore class

Introduction of three nouns:

    1. Jscontext: Provides a context for JavaScript to run
    2. Bridges of Jsvalue:javascript and objective-c data and methods
    3. Jsexport: This is an agreement that, if you interact with a protocol, your own defined protocol must comply with this Protocol

Code in ViewController.h (the code is too long, the method description is in the comment)

#import<UIKit/UIKit.h>Import Header File#import<JavaScriptCore/JavaScriptCore.h>@protocolJsobjcdelegate <jsexport>//tianbai object called JavaScript method, must be declared!!! -(void) call;-(void) Getcall: ( NSString *) callstring;  @end  @interface viewcontroller: uiviewcontroller< Uiwebviewdelegate,jsobjcdelegate> @property (nonatomic, strong) Jscontext *jscontext;  @property (strong, nonatomic) Span class= "hljs-built_in" >uiwebview *webview;  @end             

Code in VIEWCONTROLLER.M (the code is too long, the method description is in the comment)

JavaScriptCore in the Web page call native application method can be used delegate or block two methods, this article to be explained by delegate.

Set WebView

Self. WebView = [[UIWebView Alloc]initwithframe:CGRectMake (0,20, [UIScreen Mainscreen]. Bounds. Size. width, [UIScreen Mainscreen]. Bounds. Size. height)];self.webview.delegate = self; //loading HTML files from local nsstring* path = [[ nsbundle Mainbundle] pathforresource:@ "index" OfType:@ "html"]; nsurl* url = [nsurl Fileurlwithpath:path]; nsurlrequest* request = [nsurlrequest Requestwithurl:url]; [self.webview loadrequest:request]; [self.view addsubview:self< Span class= "hljs-variable" >.webview];             

JavaScript's Tianbai is an object that acts as a bridge between native apps and Web pages. Used to invoke methods

WebView Loading complete Calling agent

- (void) Webviewdidfinishload: (uiwebview *) WebView {//set Javascriptcontext context self@ "DocumentView.webView.mainFrame.javaScriptContext "]; //points Tianbai object to itself self@ "tianbai"] = self; self.jscontext.exception = Exceptionvalue; nslog (@ "Exception information:%@", exceptionvalue);};}     

After the object is pointed to itself, if the call tianbai.call() responds to the following method, the OC method calls the callback method in JS and passes the value

- (void)call{    NSLog(@"call");    // 之后在回调JavaScript的方法Callback把内容传出去    JSValue *Callback = self.jsContext[@"Callback"]; //传值给web端 [Callback callWithArguments:@[@"唤起本地OC回调完成"]];}

After you point the object to itself, if the call tianbai.getCall(callInfo) responds to the following method, only the Alercallback method in JavaScript is called in the OC method

- (void)getCall:(NSString *)callString{    NSLog(@"Get:%@", callString);    // 成功回调JavaScript的方法Callback JSValue *Callback = self.jsContext[@"alerCallback"]; [Callback callWithArguments:nil];}

After you point the object to itself, you can also inject JS into the HTML

- (void)alert{    // 直接添加提示框    NSString *str = @"alert(‘OC添加JS提示成功‘)";    [self.jsContext evaluateScript:str];}

Demo Address: Click to download



Wen/tianbai (author of Jane's book)
Original link: http://www.jianshu.com/p/fd378c6d70c0
Copyright belongs to the author, please contact the author to obtain authorization, and Mark "book author".

Reprint--Invoke and transmit values (with HTML code) based on native JS and OC methods

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.