美文网首页傲视苍穹iOS《Objective-C》VIP专题
UIWebView和JavaScript交互的那些事

UIWebView和JavaScript交互的那些事

作者: 傲视苍穹 | 来源:发表于2018-06-15 13:52 被阅读18次

index.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<div style="margin-top: 100px">
<h1>UIWebView和JavaScript交互的那些事</h1>
<input type="button" value="CallCamera" onclick="JSObject.callCamera()">
</div>
<div>
<input type="button" value="Share" onclick="callShare()">
</div>


<script>

var callShare = function() {

var shareInfo = JSON.stringify(
    {"title": "标题", 
    "desc": "内容", 
   "shareUrl": "https://www.baidu.com",
   "shareIco":"https://img.haomeiwen.com/i1220329/15e7dbbeb0825197.png?imageMogr2/auto-orient/"}
  );
   JSObject.share(shareInfo);
}

var picCallback = function(photos) {
alert(photos);

}

var shareCallback = function(){
alert('success');
}
</script>
</body>
</html>

创建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 <JavaScriptCore/JavaScriptCore.h>

创建代理

@protocol JSObjectDelegate <JSExport>

// js调用OC的方法

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

@end

控制器实现代理

@interface ViewController ()<UIWebViewDelegate,JSObjectDelegate>
@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交互的那些事

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