js调用原生OC方法

上代码。

#import "ViewController.h"
#import 

#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 ()


@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代码



    
        
            
            
            
            
                
                
                
                
                    Insert title here
    
    
        

你可能感兴趣的:(js调用原生OC方法)