UIWebView和JavaScript交互的那些事

index.html







UIWebView和JavaScript交互的那些事

创建UIWebView

    self.webView = [[UIWebView alloc]initWithFrame:self.view.frame];
    self.webView.delegate = self;
    [self.view addSubview:self.webView];
    
    NSURL *url = [[NSBundle mainBundle] URLForResource:@"index" withExtension:@"html"];
    [self.webView loadRequest:[NSURLRequest requestWithURL:url]];

设置JS交互代理

首先 import

创建代理

@protocol JSObjectDelegate 

// js调用OC的方法

- (void)callCamera;
- (void)share:(NSString *)shareInfo;

@end

控制器实现代理

@interface ViewController ()
@property(nonatomic,strong)UIWebView *webView;
@property(nonatomic,strong)JSContext *jsContext;
@end

UIWebViewDelegate 方法的实现

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    self.jsContext = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    // 设置js和oc 交互桥梁
    self.jsContext[@"JSObject"] = self;
    self.jsContext.exceptionHandler = ^(JSContext *context, JSValue *ex){
        context.exception = ex;
        NSLog(@"异常信息%@",ex);
    };
}

JSObjectDelegate 方法的实现

//js调用oc 方法
- (void)callCamera
{
    NSLog(@"调用摄像头");
    // oc 调用js方法
    JSValue *picCallBack = self.jsContext[@"picCallback"];
    [picCallBack callWithArguments:@[@"传给js中的参数"]];
}

//js调用oc 方法
- (void) share:(NSString *)shareInfo {
    NSLog(@"%@",shareInfo);
    
    // oc 调用js方法
    JSValue *shareCallBack = self.jsContext[@"shareCallback"];
    [shareCallBack callWithArguments:nil];
}

你可能感兴趣的:(UIWebView和JavaScript交互的那些事)