Reprint "iOS Development" page JS and OC Interaction (javascriptcore) OC----->JS

Source: Internet
Author: User

Goal

This paper introduces the interaction between JS and OC using the Javascriptcore.framework framework published by Apple in IOS7. The goals we want to achieve are:

    • OC invokes the JS method on the Web page
    • The OC method in the Web page JS call app
Javasciptcore.framework Framework Introduction

JavaScriptCore is an important part of WebKit, which is mainly to parse and provide execution environment for JS.
For details, please see the article in this brief book: JavaScriptCore use

Prepare the Environment
    • Create an iOS project called JS interaction Demo with OC. Then add a uiwebveiw to the storyboard and set the upper and lower left and right constraints to 0 and the background set to white.
    • The webview you just created is a property of Viewcontroller. Using WebView to load Baidu interface
    • Writing HTML files
      Because there is no ready-made Web page to meet our needs of this article, so the landlord himself did a local HTML file. As our material.
<! DOCTYPE html>
<Html Lang="EN">

<Head>
<Meta CharSet="Utf-8">
<Title>JS interacting with OC</Title>

<!--define JS functions--
<Script Type="text/JavaScript ">
functionTest1()
{
Alert("I am the JS method called by OC")
}
</Script>

</Head>
<Body>
<Br /><Br /><br /><br />

    <!--Create a button and click on the call   Printhelloworld ()   method-->
    < Button onclick= " Printhelloworld () "> print hellowold in Xcode console </button>

</body>
</html>

The code for

HTML is very simple
First, a JS function test1 () is defined in the head. Calling this function pops up an alert window.

<!--  define JS function  --> 
    <script type= "text/ java script ">
        function Test1 ()
        {
            Alert ( span class= "str" > "I am the JS method called by OC" )
        }
    </script >

Body inside creates a button, click the button will call Printhelloworld () method. The implementation of this method is not defined here, and we will define it in the OC code.

<!--Create a button, click on the call Printhelloworld () function--
<buttononclick=""> print hellowold</button> in Xcode console

OK, now we can load this local HTML file.

//
Viewcontroller.m
JS and OC Interactive Demo
//
Created by Shi on 16/7/9.
Copyright? 2016 Shixueqian. All rights reserved.
//

#import "ViewController.h"

@interfaceViewcontroller () <Uiwebviewdelegate>

WebView
@property(Weak,Nonatomic) Iboutlet UIWebView *WebView;

@end

@implementationViewcontroller

- (void)Viewdidload{
[SuperViewdidload];

Setting up the WebView agent
Self.WebView.Delegate = Self;

Get Local HTML path
NSString *Path= [[NSBundleMainbundle]Pathforresource:@"Index.html"OfType:Nil];
Chinese path to Transcode
Path= [Path stringbyaddingpercentescapesusingencoding:Nsutf8stringencoding];

Loading HTML
Nsurl*Url= [NsurlURLWithString:Path];
Nsurlrequest *Request= [NsurlrequestRequestwithurl:url;
    [self. WebView loadrequest:request];
}

-(void ) webviewdidfinishload:(uiwebview *) webview {
    Nslog@ "page loading complete" }

@end

Environment ready to finish, start

OC invokes the JS method on the Web page

Our HTML file defines a JS method Test1 (), and now we're going to call this method

    • Import Javascriptcore.framework first. Project->build phases->link Binary with libraries-> click "+", enter "JavaScriptCore"->add
    • Import header file #import <JavaScriptCore/JavaScriptCore.h> in VIEWCONTROLLER.M.

    • Write code

- (void)Webviewdidfinishload:(UIWebView *)WebView{
NSLog(@"Web page loading complete");

[SelfDemo1];
}

- (void)Demo1{
//create Jscontext object, (here through the current WebView key get to Jscontext)
    jscontext *context =< Span class= "PLN" > [self. WebView valueforkeypath:@ "DocumentView.webView.mainFrame. java scriptcontext "";

    //oc call js method
    [context evaluatescript:@ "test1 ( ) "";
} /span>
  • After running, an alert window pops up, proving that the JS method on the HTML test1 is called.

  • The above code is non-parametric, the addition is parameter?
    We add a JS method Test3 (A, B) to the HTML file. The method has two parameters.

    <!--define JS functions--
    <Script type= "Text/java script ">
          Function Test3 (a,b< Span class= "pun" >)
          {
              Alert ( "I am the JS method called by OC" + a + B)
          }
      </script< Span class= "pun" >>

    and call it in VIEWCONTROLLER.M.

-(void)Webviewdidfinishload:(UIWebView *)WebView{
NSLog(@"Web page loading complete");

[Self demo1];
[SelfDemo2];
}

OC calls the JS method with multiple parameters
- (void)Demo2{
Create a Jscontext object
Jscontext*Context = [self. WebView valueforkeypath:@"DocumentView.webView.mainFrame. JavaScriptContext "];
[context Evaluatescript:@"test1 (/" I am parameter a/",/" I am parameter b/ ")"];
}< /c11>

The result of the operation is:

    • Above is the JS method defined in the OC call HTML. We can also write a section of the iOS program JS code to invoke.
-(void)Webviewdidfinishload:(UIWebView *)WebView{
NSLog(@"Web page loading complete");

[Self demo1];
[Self demo2];
[SelfDemo3];
}

OC calls OC code to write out the JS method
- (void)Demo3{
Create a Jscontext object
Jscontext *Context= [Self.WebView Valueforkeypath:@"DocumentView.webView.mainFrame.JavaScriptContext "];
JS Code
nsstring *jscode = [nsstring stringwithformat:@"alert (/" I am OC inside the JS method/")"];

//oc Call JS method
[context evaluatescript:jscode];
}< /c11>

The results of the operation are as follows:

Reprint "iOS Development" page JS and OC Interaction (javascriptcore) OC----->JS

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.