前提:在iOS控制器中加载UIWebView,设置代理,遵守UIWebViewDelegate协议。
966882-20160613164528792-177708558.jpg一、iOS调用JS方法
通过iOS调用JS代码实现起来比较方便直接调用UIWebView的方法- (nullable NSString *)stringByEvaluatingJavaScriptFromString:(NSString *)script;
1.查询标签
// 查询标签
NSString *str = @"var word = document.getElementById('word');"
@"alert(word.innerHTML)";
[webView stringByEvaluatingJavaScriptFromString:str];
2.为网页添加标签:
NSString *str = @"var img = document.createElement('img');"
"img.src = 'icon5.jpg';"
"img.width = 300;"
"img.heigth = 100;"
"document.body.appendChild(img);";
[webView stringByEvaluatingJavaScriptFromString:str];
3.删除网页标签:
// 删除标签
NSString *str1 = @"var word = document.getElementById('word');"
@"word.remove();";
[webView stringByEvaluatingJavaScriptFromString:str1];
4.更改标签:
// 更改
NSString *str2 = @"var change = document.getElementsByClassName('change')[0];"
"change.innerHTML = 'hello';";
NSString *result = [webView stringByEvaluatingJavaScriptFromString:str2];
HTML端代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>iOS和H5交互</title>
</head>
<body>
<p id="word">6666666666</p>
<ul>
<li class="change">111111</li>
<li class="haha">222222</li>
<li>333333</li>
<li>444444</li>
</ul>
<input class="name" placeholder="请输入密码">
<button onclick="buttonClick()">提交信息</button>
<script type="text/javascript">
alert('这个一个弹框');
</script>
</body>
</html>
二、JS调用iOS方法:
1.第一种方法比较简单,通过字符串的比对。这种方式iOS端代码比较简单,网页加载完成后后台需要重新定义网页url,将移动端需要的参数拼接到url上返回,或者按照和后台约定好的字段来进行字符串比对以达到调用iOS方法的目的。下面贴代码。
oc代码:(需要实现webView的协议)
// 拦截协议头,调取系统摄像头
#pragma mark UIWebViewDelegate
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType: (UIWebViewNavigationType)navigationType
{
NSString *str = request.URL.absoluteString;
if ([str containsString:@"wxd://"]) {
[self getImage];
}
return YES;
}
- (void)getImage
{
if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) { //调用相册
//实例化控制器
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
picker.delegate = self;
// 是否有图片选取框
picker.allowsEditing = YES;
[self presentViewController:picker animated:YES completion:nil];
}
}
HTML端代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>在html中调用oc的方法</title>
</head>
<body>
<button onclick="getImage()">访问相册</button>
<script type="text/javascript">
function getImage(){
window.location.href = "wxd://getImage";
}
</script>
</body>
</html>
2.第二种方法,JS直接用oc方法名来调用oc方法,类似于安卓.addJavascriptInterface(new JsObject(), "Android")方法,头文件需要导入#import <JavaScriptCore/JavaScriptCore.h>。
首先创建一个继承自NSObject的类,在这里我命名为JSTestObjext,.h代码如下:
966882-20160613171731245-1295359900.png
.m中实现协议方法,代码如下:
966882-20160613171849104-1312256177.png之后在加载webView的控制器中调用:
966882-20160613172158401-1739766841.png到此为止,oc代码就已经写完了,我们只需告诉JS端使用testobject类,就可以调oc的方法了。下面附上JS调用的代码:
966882-20160613172532198-955522503.png
网友评论