iOS OC -JS 相互调用

工程代码如下
1、OC代码

//
//  ViewController.m
//  OCJSTest
//
//  Created by 冯闯 on 2022/1/25.
//

#import "ViewController.h"
#import 
@interface ViewController ()
@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 代码




    
    这是一个网页
    




这里是一个网页

经过仔细研究 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 
@interface ViewController ()
@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> 遵守协议,实现其方法.
    //   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 代码




    
    这是一个网页
    




这里是一个网页

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

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

你可能感兴趣的:(iOS OC -JS 相互调用)