oc 和JS 交互 主要是用到UIWebView 的这个方法 - (nullableNSString *)stringByEvaluatingJavaScriptFromString:(NSString *)script; 去调用JS,下面为大家演示一个小demo。显示结果为:
首先,自己写一个Html 网页,放到空文件中,不会写的可以在网页上 下一个,或者到 W3school 去 找一个demo,,再不会写的,看下面:
<html>
<head>
<title>JS和OC的交互</title>
<meta http-equiv="Content-Type"content="text/html; charset=UTF-8">
<script>
function test()
{
alert("JS和OC的交互");
return"交互成功";
}
</script>
<body>
<br/>
<br/>
<br/>
<a href='ios://openMyAlbum'>打开相机</a><br/>
<a href='ios://openBaidu'>打开百度</a>
<a href = 'ios://openMyCamera'>打开相册</a>
<svg xmlns="http://www.w3.org/2000/svg"version="1.1"height="190">
<polygonpoints="100,10 40,180 190,60 10,60 160,180"
style="fill:lime;stroke:purple;stroke-width:5;fill-rule:evenodd;" />
</svg>
</body>
</html>
接着在试图控制器中写入下面方法就可:
_webView = [[UIWebViewalloc] initWithFrame:self.view.bounds];
[self.viewaddSubview:_webView];
NSString *path = [[NSBundlemainBundle] pathForResource:@"text.html"ofType:nil];
NSURL *url = [NSURLfileURLWithPath:path];
NSURLRequest *req = [[NSURLRequestalloc] initWithURL:url];
_webView.delegate =self;
_webView.dataDetectorTypes =UIDataDetectorTypeAll;
[_webViewloadRequest:req];
}
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
NSString *title = [webViewstringByEvaluatingJavaScriptFromString:@"document.title"];
NSString *url = [webViewstringByEvaluatingJavaScriptFromString:@"document.location.href"];
NSLog(@"title=%@,url=%@",title,url);
NSString *urlstr = request.URL.absoluteString;
NSLog(@"%@",urlstr);
NSRange range = [urlstrrangeOfString:@"ios://"];
if(range.length!=0)
{
NSString *method = [urlstrsubstringFromIndex:(range.location+range.length)];
SEL selctor =NSSelectorFromString(method);
[selfperformSelector:selctor withObject:nilafterDelay:1.0];
}
returnYES;
}
-(void)openMyAlbum
{
UIImagePickerController
*vc = [[UIImagePickerController
alloc]init];
vc.sourceType
= UIImagePickerControllerSourceTypePhotoLibrary;
[self
presentViewController:vc
animated:YES
completion:nil];
}
-(void)openMyCamera
{
}
-(void)openBaidu{
[_webViewstringByEvaluatingJavaScriptFromString:@"test();"];
return;
}