iOS开发oc与js相互调用的方式方法

文章主要是介绍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; 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();"];

//传参数给js

NSString *getValue = [NSString stringWithFormat:@"javascript:LoadData('%@','%@','%@','%@','%@','%@','%@')",@"1",[BDSingleton sharedSingle].username,[BDSingleton sharedSingle].token,thisGroupid,kBaseWebViewLocationURL,conditionStr,colorString];

    [webView stringByEvaluatingJavaScriptFromString:getValue];

对应

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"] = ^(NSString *str) {

        NSLog(@"js调用oc---------begin-------拿到 js穿的参数-%@",str);

        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();"];

    };

需要注意的 感觉

@"documentView.webView.mainFrame.javaScriptContext"这个就是这样写,不用管.直接copy

需要注意的就是

content[@"bdgt"]   中的bdgt这个需要跟js中的

bdgt("hello world"); 对应上.

全文完毕,谢谢查看,附上demo链接:

 JSAndOC重新整理的.zip

原文地址:https://www.cnblogs.com/godlovexq/p/5691942.html