美文网首页
ios 开发OC 和 JS 交互

ios 开发OC 和 JS 交互

作者: 微笑城ios | 来源:发表于2019-03-22 11:10 被阅读0次

ios 开发OC 和 JS 交互

最近遇到了关于 oc 和 js 交互的功能, 记录一下就当是是做了笔记的

开发环境准备

  • xcode

  • WebStorm 非常好用的 html 开发工具, 当然也可以使用 vscode

  • 下面的html 代码片段


<!DOCTYPE html>

<html lang="en">

<head>

    <meta name = "viewport" content="width=device-width,initial-scale=1.0 user-scalable = no , maximum-scale=1.0">

    <meta charset="UTF-8">

    <title>显示图片</title>

    <style>

        body{

            background-color: aliceblue;

            padding: 10px;

        }

        *{

            margin: 0;

            padding: 0;

        }

        .header_image{

            width: 100%;

        }

        .body_image{

            width: 33.3%;

        }

    </style>

    <script type="text/javascript">

        <!--图片的点击事件-->

        function imageClcik($event) {

            // confirm('点击了图片 : ' + $event);

            let img = window.document.getElementById($event).setAttribute('src','http://192.168.100.9/img/banner/banner1.jpg');

            console.log(img);

            // img.setAttribute('src','http://192.168.100.9/img/banner/banner1.jpg');

        }

        function  textClick($event) {

        }

        function changeImage($image_id, $image_url) {

            let img = window.document.getElementById($image_id).setAttribute('src',$image_url);

        }

    </script>

</head>

<body>

<div>

    <h3 id="title" onclick="textClick('title')">*title*</h3>

    <label>价格 : *price*¥</label>

    <br>

    <img class="header_image" id="header_img" src="*header_img*" onclick="imageClcik('header_img')">

    <img class="body_image" id="img_left" src="*img_left*" onclick="imageClcik('img_left')"><img id="img_middle" class="body_image" src="*img_middle*" onclick="imageClcik('img_middle')"><img id="img_right" class="body_image" src="*img_right*" onclick="imageClcik('img_right')">

</div>

</body>

</html>

搭建 WebView


#import <WebKit/WebKit.h>

// JavaScript 和 oc 相互调用核心

#import <JavaScriptCore/JavaScriptCore.h>

@interface ViewController ()<UIWebViewDelegate>

// 声明 webview

@property (nonatomic, strong) UIWebView *mywebview;

// 记录 html 点击事件

@property (nonatomic, copy) NSString *current_html_id;

@end

// 这个地方你可以根据自己事情 情况去搭建

static NSString *baseIp = @"http://192.168.100.9/html/imageTest.html";

@implementation ViewController

- (void)viewDidLoad {

    [super viewDidLoad];

    [self.view addSubview:self.mywebview];

    // 添加 用来点击的按钮

    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];

    [button setTitle:@"点我 我会换图片" forState:UIControlStateNormal];

    [button addTarget:self action:@selector(changeImage) forControlEvents:UIControlEventTouchUpInside];

    button.frame = CGRectMake(100, 100, 100, 100);

    [self.view addSubview:button];

}

加载显示 html


//懒加载

- (UIWebView *)mywebview

{

    if (!_mywebview) {

        _mywebview = [[UIWebView alloc] initWithFrame:self.view.bounds];

        NSURL *url = [NSURL URLWithString:baseIp];

//  加载显示方式一  直接以 request 方式加载显示 缺点看到不html 片段

//        NSURLRequest *request = [NSURLRequest requestWithURL:url];

//        NSLog(@"request");

//        [_mywebview loadRequest:request];

//    显示方式二  显示 html 替换里面的内容为自己想要的, 我替换了图片和标题

        NSString *htmlString = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];

        NSLog(@"html : %@", htmlString);

        htmlString = [htmlString stringByReplacingOccurrencesOfString:@"*title*" withString:@"苹果8 只要1800 全新原装"];

        htmlString = [htmlString stringByReplacingOccurrencesOfString:@"*price*" withString:@"1800"];

        htmlString = [htmlString stringByReplacingOccurrencesOfString:@"*header_img*" withString:@"http://192.168.100.9/img/clothes/clothes_1.jpeg"];

        htmlString = [htmlString stringByReplacingOccurrencesOfString:@"*img_left*" withString:@"http://192.168.100.9/img/clothes/clothes_2.jpeg"];

        htmlString = [htmlString stringByReplacingOccurrencesOfString:@"*img_middle*" withString:@"http://192.168.100.9/img/clothes/clothes_3.jpeg"];

        htmlString = [htmlString stringByReplacingOccurrencesOfString:@"*img_right*" withString:@"http://192.168.100.9/img/clothes/clothes_4.jpeg"];

        _htmlString = htmlString;

        [_mywebview loadHTMLString:htmlString baseURL:url];

//  代理监听 加载状态

        _mywebview.delegate = self;

    }

    return _mywebview;

}

js 调用 oc


// 代理方法 UIWebViewDelegate --- 页面加载完毕

- (void)webViewDidFinishLoad:(UIWebView *)webView{

    /*

    这里常用来 做tableviewCell 嵌套的 cell 高度的适配 ,

    使用UIWebView 的主要原因 也是因为个人觉得 比WKWebView好用, 获取高度稳定

    */

    // JSContext 这玩意叫啥 我不知道 , 百度了一下  有网友介绍 : 这是 JavaScriptCore 核心的里面的东西 ^_^ 且用吧

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

    // 监听后台返回的方法名称

    contest[@"imageClcik"] = ^(NSString *itme){

        // 能看到打印输出 说明方法调用成功

        NSLog(@"item : %@", itme);

        // 记录当前点击的元素的id  后面用到

        self.current_html_id = itme;

    };

}

更换图片的方法 ---> oc 调用js


- (void )changeImage{

    if (_current_html_id != nil) {

        // 需要替换的 img 地址

        NSString *imgPath = @"http://192.168.100.9/img/banner/banner1.jpg";

        // 方法一 直接操作 DOM

        // 需要产生效果的 JavaScript 需要执行的效果 : 这段效果就是 替换img 标签的 src 属性

        NSString *dome = [NSString stringWithFormat:@"window.document.getElementById('%@').setAttribute('src','%@')",self.current_html_id,imgPath];



        // 执行 JavaScript 片段

        [self.mywebview stringByEvaluatingJavaScriptFromString:dome];



        /*

        // 方法二  oc 调用 js 方法

        NSString *action = [[NSString stringWithFormat:@"changeImage('%@','%@')",self.current_html_id,imgPath];]

        [self.mywebview stringByEvaluatingJavaScriptFromString:action];

        */

        // 置空 避免没意义的重复操作

        _current_html_id = nil;

    }

}

最终实现的效果是 : 点击图片的时候, 会打印img元素的id, 点击保存图片的 会更换图片, 效果明显

给大家留了练习题

  1. 如果修改文字 该如何实现

  2. 修改完文字 如果显示回去

尾声

  • 核心东西就是这么多啦, 面试可能会有人问到. 多学多记 还是有好处的 , 代码就这么多, 需要的dome的同学可以留言 替换图片地址基本上可以了, html文本 你们采用本地加载就ok了; 我是自己搭建的 Apache 服务;

相关文章

网友评论

      本文标题:ios 开发OC 和 JS 交互

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