js调用原生OC方法

2017-07-04  本文已影响97人  LH_0811

上代码。

#import "ViewController.h"
#import <JavaScriptCore/JavaScriptCore.h>

#define RandomColor      [UIColor colorWithRed:arc4random_uniform(255)/255.0 green:arc4random_uniform(255)/255.0 blue:arc4random_uniform(255)/255.0 alpha:1.0f];
@interface ViewController ()<UIWebViewDelegate>


@property (weak, nonatomic) IBOutlet UIWebView *webView;

@property (nonatomic,copy) NSString * htmlStr;

@end

@implementation ViewController

#pragma mark -- 懒加载
- (NSString *)htmlStr
{
    if (_htmlStr == nil) {
        NSString *filePath = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"html"];
        NSData *data = [[NSData alloc]initWithContentsOfFile:filePath];
        NSString * htmlStr = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
        _htmlStr = htmlStr;
    }
    return _htmlStr;
}

#pragma mark -- 生命周期
- (void)viewDidLoad{
    [super viewDidLoad];
    
    NSLog(@"html:%@",self.htmlStr);
    self.webView.delegate = self;//设置代理
    [self.webView loadHTMLString:self.htmlStr baseURL:nil];//加载页面
    
    
}


#pragma -- webView delegate
//注意一点。这里向页面注入js方法,建议在webview加载完页面之后的代理里面进行。
//确保可以获取html的js上下文。以便将方法插入到js上下文中
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    NSLog(@"网页加载完毕");
    //获取到js的上下文
    JSContext * context = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    
  //注入方法
    context[@"hello"]= ^(){
        UIAlertController * alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"点击了 hello" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction * action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        [alert addAction:action];
        [self presentViewController:alert animated:YES completion:nil];
    };
    
    context[@"sure"]= ^(){
        
        UIAlertController * alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"点击了 sure" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction * action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        [alert addAction:action];
        [self presentViewController:alert animated:YES completion:nil];
    };
    
    
   
    
    context[@"change"]= ^(){
        self.webView.backgroundColor = RandomColor;
    };
    
}
@end

HTML代码

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
            <!-- JQuery -->
            <script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
            <!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
            <link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
                <!-- 最新的 Bootstrap 核心 JavaScript 文件 -->
                <script src="https://cdn.bootcss.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
                <!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
                <link rel="stylesheet" href="${pageContext.request.contextPath }/style/news.css">
                    <title>Insert title here</title>
    </head>
    <body>
        <div class="container">
            <button onclick="hello()" type="button" class="btn btn-primary btn-lg btn-block">hello button</button>
            <button onclick="sure()" type="button" class="btn btn-default btn-lg btn-block">sure button</button>
            <button onclick="change()" type="button" class="btn btn-default btn-lg btn-block">change button</button>
        <div>
    </body>
</html>
上一篇下一篇

猜你喜欢

热点阅读