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

//傳參數給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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM