JS與OC中的方法相互調用

來源:互聯網
上載者:User

標籤:blank   frame   htm   white   載入網頁   begin   for   lov   should   

文章主要是介紹oc如何調用js 以及js的代碼調用oc的方法 

先上代碼後做解釋

//oc的.m 的代碼

//ps接下來有js的代碼一併解析,最後會附上demo

//  ViewController.m

//  JSAndOC

//

//  Created by dongqiangfei on 16/7/21.

//  Copyright ? 2016年 dongqiangfei. All rights reserved.

//

 

#import "ViewController.h"

#import <JavaScriptCore/JavaScriptCore.h>

 

@interface ViewController ()<UIWebViewDelegate>

@property(nonatomic,strong)UIWebView *webView;

@end

 

@implementation ViewController

 

- (void)viewDidLoad {

    [super viewDidLoad];

    [self makeBtn];

    [self makeWeb];

    // Do any additional setup after loading the view, typically from a nib.

}

 

-(void)makeBtn

{

    UIButton *thisBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];

    thisBtn.frame = CGRectMake(100, 100, 140, 40);

    [thisBtn addTarget:self action:@selector(ocCallJS) forControlEvents:UIControlEventTouchUpInside];

    [thisBtn setTitle:@"點擊oc調用js" forState:UIControlStateNormal];

    [self.view addSubview:thisBtn];

}

 

-(void)ocCallJS

{

    [self.webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"showTitleMessage(‘%@‘)",@"oc調用了js的內容"]];

}

 

-(void)makeWeb

{

    self.webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 200, self.view.frame.size.width, self.view.frame.size.height - 200)];

    self.webView.backgroundColor = [UIColor whiteColor];

    self.webView.scalesPageToFit = YES;

    self.webView.delegate = self;

    

    NSString *webPath = [[NSBundle mainBundle] pathForResource:@"ocandjs" ofType:@"html"];

    NSURL *webURL = [NSURL fileURLWithPath:webPath];

    NSURLRequest *URLRequest = [[NSURLRequest alloc] initWithURL:webURL];

    [self.webView loadRequest:URLRequest];

    [self.view addSubview:self.webView];

    

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

    content[@"bdgt"] = ^() {

        NSLog(@"js調用oc---------begin--------");

        NSArray *thisArr = [JSContext currentArguments];

        for (JSValue *jsValue in thisArr) {

            NSLog(@"=======%@",jsValue);

        }

        //JSValue *this = [JSContext currentThis];

        //NSLog(@"this: %@",this);

        NSLog(@"js調用oc---------The End-------");

        [self.webView stringByEvaluatingJavaScriptFromString:@"show();"];

    };

}

 

- (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

 

@end

 

//js的代碼

<html>

    <!--描述網頁資訊-->

    <head>

        <meta charset="UTF-8"/>

        <title>iOS上webView與JS互動的之oc調用js的demo</title>

        <script>

            function show()

            {

                alert(‘js調用了oc的代碼‘);

            }

            function showTitle()

            {

                alert(document.title);

            }

            function showTitleMessage(message)

            {

                alert(message);

            }

            function repost()

            {

                location.href = "http://www.iosxxx.com";

            }

            function sum()

            {

                return 1 + 1;

            }

            function btnClick()

            {

                bdgt("hello world");

<!--xmg://sendMessageWithNumber_andContent_?10086&love-->

                location.href = "xmg://callWithNumber_?15830654880";

            }

        </script>

    </head>

    <!--網頁具體內容-->

    <body>

        <br>下面是網頁</br><br/>

        <button style = "background: yellow; height: 150px; width: 350px;" onclick = "btnClick();">點擊按鈕js調用oc</button>

    </body>

 

</html>

 

解析oc調用js的方法

知道的這麼一種方法如下:

[self.webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"showTitleMessage(‘%@‘)",@"oc調用了js的內容"]];

對應

function showTitleMessage(message)

或者

[self.webView stringByEvaluatingJavaScriptFromString:@"show();"];

對應

function show()           

這個方法都對應js的相應的方法.如上

使用oc調動js 注意寫法如:

[NSString stringWithFormat:@"showTitleMessage(‘%@‘)",@"oc調用了js的內容"]不能寫成

[NSString stringWithFormat:@"showTitleMessage(%@)",@"oc調用了js的內容"],否則調不起.

 

js調用  oc 的方法

這個主要是指的點擊網頁上的特定的方法調用原生的的特定方法 這個有一種簡單粗暴地方法,不懂得名字, 就是直接吊起的如

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

{

    if ([[NSString stringWithFormat:@"%@",request.URL] isEqualToString:@"特定的串連"]) {

        NSLog(@"吊起oc的方法");

    }

    return NO;//不載入網頁

    return YES;//載入網頁

}

 

直接在點擊網頁的某個方法載入網頁之前,在代理中拿到將要載入的網頁,去做相應的判斷.最早就是這樣做,也有局限性吧,但是這樣感覺比單純的js調用原生效率要高點.

 

 

接下來言歸正傳介紹正宗的js如何調用oc

如下核心方法也就這麼點

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

    content[@"bdgt"] = ^() {

        NSLog(@"js調用oc---------begin--------");

        NSArray *thisArr = [JSContext currentArguments];

        for (JSValue *jsValue in thisArr) {

            NSLog(@"=======%@",jsValue);

        }

        //JSValue *this = [JSContext currentThis];

        //NSLog(@"this: %@",this);

        NSLog(@"js調用oc---------The End-------");

        [self.webView stringByEvaluatingJavaScriptFromString:@"show();"];

    };

 本文摘自iOS攻城獅:http://www.cnblogs.com/godlovexq/p/5691942.html

JS與OC中的方法相互調用

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.