UIWebView
的浏览器的
JavaScript
中, 没有相关的接口可以调用
Objective-C
的相关方法. 一般采用
JavaScript
在浏览器环境中发出
URL
请求,
Objective-C
截获请 求以获取相关请求的思路.在
Objective-C
中在实现
UIWebViewDelegate
,然后回调UIWebview的
-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
函数,在上面这个函数中,通过截取NSURLRequest解析js中传递过来的参数,再根据参数来选择早已定义好的方法。
2、JavaScriptCore
, 使的JavaScript
和 Objective-C
可以互操作.
test.html
<html>
<head lang="en">
<meta charset="UTF-8">
</head>
<body>
<div>
<input type="button" value="CallCamera" οnclick="callCamera()">
</div>
<script>
function callCamera() {
jakilllog("hello world");
}
</script>
</body>
</html>
//点击button调用OC的方法
#import <JavaScriptCore/JavaScriptCore.h>
#import "ViewController1.h"
#import <WebKit/WebKit.h>
@protocol JSObjcDelegate <JSExport>
- (void)callCamera;
- (void)share:(NSString *)shareString;
- (void)push;
@end
@interface ViewController ()<UIWebViewDelegate,JSObjcDelegate,WKNavigationDelegate>
@property (nonatomic,strong) JSContext *jsContext;
@property (weak,nonatomic) IBOutlet UIWebView *myWebView;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
NSURL *url = [[NSBundle mainBundle] URLForResource:@"test2" withExtension:@"html"];
self.myWebView.delegate = self;
[self.myWebView loadRequest:[[NSURLRequest alloc] initWithURL:url]];
}
- (void)webViewDidFinishLoad:(UIWebView *)webView{
self.jsContext = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];//获取webView的javaScript环境
//Block 方法
self.jsContext[@"jakilllog"] = ^() {
NSLog(@"Begin Log");
NSArray *args = [JSContext currentArguments];
for (JSValue *jsVal in args) {
NSLog(@"%@", jsVal);
}
JSValue *this = [JSContext currentThis];
NSLog(@"-------End Log-------");
};
}在定义的webview中,如果使用js执行log这个函数,会调用上面oc中block段代码
// delegate 方法
- (void)webViewDidFinishLoad:(UIWebView *)webView{
self.jsContext = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
NSLog(@"%@",self.jsContext);
self.jsContext[@"Toyun"] = self;
self.jsContext.exceptionHandler = ^(JSContext *context,JSValue *exceptionValue){
context.exception = exceptionValue;
NSLog(@"异常信息:%@",exceptionValue);
};
}
- (void)callCamera{
NSLog(@"callCamera");
// 获取到照片之后在回调js的方法picCallback把图片传出去
JSValue *picCallback = self.jsContext[@"picCallback"];
[picCallback callWithArguments:@[@"myPhotos"]];
}
- (void)share:(NSString *)shareString{
NSLog(@"share:%@", shareString);
// 分享成功回调js的方法shareCallback
JSValue *shareCallback = self.jsContext[@"shareCallback"];
[shareCallback callWithArguments:nil];
}