美文网首页
iOS OC -JS 相互调用

iOS OC -JS 相互调用

作者: 奋斗的小马达 | 来源:发表于2022-01-26 10:54 被阅读0次

    工程代码如下
    1、OC代码

    //
    //  ViewController.m
    //  OCJSTest
    //
    //  Created by 冯闯 on 2022/1/25.
    //
    
    #import "ViewController.h"
    #import <WebKit/WebKit.h>
    @interface ViewController ()<WKNavigationDelegate,UIScrollViewDelegate>
    @property (nonatomic,strong)WKWebView *webview;
    @property (nonatomic,assign)NSInteger count;
    @end
    
    @implementation ViewController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        self.view.backgroundColor = [UIColor greenColor];
        self.webview = [[WKWebView alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 400)];
        [self.view addSubview:self.webview];
        NSURL *url = [[NSBundle mainBundle ] URLForResource:@"index" withExtension:@"html"];
        NSURLRequest *requst = [NSURLRequest requestWithURL:url];
        [self.webview loadRequest:requst];
        self.webview.backgroundColor = [UIColor redColor];
        self.webview.navigationDelegate = self;
        self.count = 0;
        UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(50, [UIScreen mainScreen].bounds.size.height-100, [UIScreen mainScreen].bounds.size.width-100, 40)];
        [btn setTitle:@"本地调用JS方法" forState:UIControlStateNormal];
        [btn addTarget:self action:@selector(btnAction) forControlEvents:UIControlEventTouchUpInside];
        btn.backgroundColor = [UIColor orangeColor];
        [self.view addSubview:btn];
    }
    
    
    - (void)btnAction{
        //1. webview调用JS函数, JS代码可根据需要拼接好。
        self.count += 1;
        NSString *jsFunc = [NSString stringWithFormat:@"showalert(%ld)",(long)self.count];
        [self.webview evaluateJavaScript:jsFunc completionHandler:^(id _Nullable result, NSError * _Nullable error) {
            NSLog(@"evaluateJavaScript:\n result = %@ error = %@",result, error);
        }];
    }
    
    #pragma mark -- 网页加载完毕
    - (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
        NSLog(@"加载完成");
    }
    
    //加载失败
    - (void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error {
        NSLog(@"加载失败1");
    }
    
    //加载失败
    - (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error {
        NSLog(@"加载失败2");
    }
    
    - (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
        NSLog(@"啦啦啦");
    }
    
    @end
    
    

    2、html 代码

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>这是一个网页</title>
        <style>
    
            #content{
                display: flex;
                justify-content: space-between;
                flex-direction: column;
                background-color: blue;
                height: 1000px;
                width: 100%;
            }
    
            .topP{
                line-height: 180px;
                font-size: 80px;
                background-color: green;
                text-align: center;
                margin-left: 50px;
                margin-right: 50px;
            }
    
            .bottomButton{
                font-size: 80px;
                background-color: gold;
                line-height: 180px;
                margin-left: 50px;
                margin-right: 50px;
                margin-bottom: 50px;
            }
        </style>
    
    </head>
    <body>
    
    <div id="content">
        <p class="topP"  >  这里是一个网页 </p>
        <button class="bottomButton"  >点击调用OC方法</button>
    </div>
    
    </body>
    
    <script>
    
      function showalert(message) {
            var pp = document.getElementsByClassName('topP')[0]
            pp.innerHTML = '本地改变第(' + message + ')次'
        }
    
    </script>
    
    </html>
    

    经过仔细研究 OC 调用JS 还是很简单的

    OC调用JS函数, JS代码可根据需要拼接好。
    如下图:


    596FCDC135E86D77D23D66E52D383099.png

    OC 直接将JS代码 封装成字符串 然后通过
    evaluateJavaScript 方法将字符串注入JS
    然后JS 接受到OC传过来的字符串 然后解析 最后调用

    JS调用OC

    OC代码

    //
    //  ViewController.m
    //  OCJSTest
    //
    //  Created by 冯闯 on 2022/1/25.
    //
    
    #import "ViewController.h"
    #import <WebKit/WebKit.h>
    @interface ViewController ()<WKNavigationDelegate,UIScrollViewDelegate,WKScriptMessageHandler>
    @property (nonatomic,strong)WKWebView *webview;
    @property (nonatomic,assign)NSInteger count;
    @end
    
    @implementation ViewController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        self.view.backgroundColor = [UIColor greenColor];
     
        // 2. 网页JS调原生:
        //   1> 需要先设置Webview.config 的WKUserContentController
        //   2> 注册方法名 [userCC addScriptMessageHandler:self name:];
        //   3> 遵守协议<WKScriptMessageHandler>,实现其方法.
        //   4> 在控制器销毁时,需要移除方法名注册
    
        WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
        configuration.selectionGranularity = WKSelectionGranularityCharacter;
        configuration.userContentController = [WKUserContentController new];
        [configuration.userContentController addScriptMessageHandler:self name:@"changeviewColor"];
    
        self.webview = [[WKWebView alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 400) configuration:configuration];
    
        
        [self.view addSubview:self.webview];
        NSURL *url = [[NSBundle mainBundle ] URLForResource:@"index" withExtension:@"html"];
        NSURLRequest *requst = [NSURLRequest requestWithURL:url];
        [self.webview loadRequest:requst];
        self.webview.backgroundColor = [UIColor redColor];
        self.webview.navigationDelegate = self;
        self.count = 0;
        UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(50, [UIScreen mainScreen].bounds.size.height-100, [UIScreen mainScreen].bounds.size.width-100, 40)];
        [btn setTitle:@"本地调用JS方法" forState:UIControlStateNormal];
        [btn addTarget:self action:@selector(btnAction) forControlEvents:UIControlEventTouchUpInside];
        btn.backgroundColor = [UIColor orangeColor];
        [self.view addSubview:btn];
    }
    
    
    /*
     这里是h5发送过来的消息,这里有多个控制器要加载,通过model属性去判断就可以了
     @param userContentController userContentController description
     @param message 根据messageName来判断是什么类型的操作
     */
    - (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
        NSLog(@"%@--%@",message.name,message.body);
        if ([message.name isEqualToString:@"changeviewColor"]) {
            [self changeviewColor];
        }
    }
    
    
    
    - (void)btnAction{
    //    1. webview调用JS函数, JS代码可根据需要拼接好。
        self.count += 1;
        NSString *jsFunc = [NSString stringWithFormat:@"showalert(%ld)",(long)self.count];
        [self.webview evaluateJavaScript:jsFunc completionHandler:^(id _Nullable result, NSError * _Nullable error) {
            NSLog(@"evaluateJavaScript:\n result = %@ error = %@",result, error);
        }];
    }
    
    #pragma mark -- 网页加载完毕
    - (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
        NSLog(@"加载完成");
        
        
        
    }
    
    //加载失败
    - (void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error {
        NSLog(@"加载失败1");
    }
    
    //加载失败
    - (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error {
        NSLog(@"加载失败2");
    }
    
    - (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
        NSLog(@"啦啦啦");
    }
    
    - (void)changeviewColor{
        
        NSArray *colorArr = @[[UIColor yellowColor],[UIColor blueColor],[UIColor redColor],[UIColor cyanColor]];
        int value = arc4random() % colorArr.count;
        
        self.view.backgroundColor = colorArr[value];
    }
    
    
    @end
    
    

    JS 代码

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>这是一个网页</title>
        <style>
    
            #content{
                display: flex;
                justify-content: space-between;
                flex-direction: column;
                background-color: blue;
                height: 1000px;
                width: 100%;
            }
    
            .topP{
                line-height: 180px;
                font-size: 80px;
                background-color: green;
                text-align: center;
                margin-left: 50px;
                margin-right: 50px;
            }
    
            .bottomButton{
                font-size: 80px;
                background-color: gold;
                line-height: 180px;
                margin-left: 50px;
                margin-right: 50px;
                margin-bottom: 50px;
            }
        </style>
    
    </head>
    <body>
    
    <div id="content">
        <p class="topP"  >  这里是一个网页 </p>
        <button class="bottomButton" onclick="btnAction()" >点击调用OC方法</button>
    </div>
    
    </body>
    
    <script>
    
      function showalert(message) {
            var pp = document.getElementsByClassName('topP')[0]
            pp.innerHTML = '本地改变第(' + message + ')次'
        }
        
        function btnAction(){
            window.webkit.messageHandlers.changeviewColor.postMessage('333');
        }
    
    </script>
    
    </html>
    
    

    其实 JS调用OC方法也很简单 主要实现以下几个步骤即可

    1. 网页JS调原生:
      1> 需要先设置Webview.config 的WKUserContentController
      2> 注册方法名 [userCC addScriptMessageHandler:self name:];
      3> 遵守协议<WKScriptMessageHandler>,实现其方法.
      4> 在控制器销毁时,需要移除方法名注册

    相关文章

      网友评论

          本文标题:iOS OC -JS 相互调用

          本文链接:https://www.haomeiwen.com/subject/frcnhrtx.html