1. JS调用OC的方法
实现方式1:JS调用原声OC
原理:相当于是JS端发起一个假的URL请求, 然后用代理方法去拦截这次请求,做相应的处理。
JS端:
<html>
<header>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript">
function showAlert(message){
alert(message);
}
function loadURL(url) {
var iFrame;
iFrame = document.createElement("iframe");
iFrame.setAttribute("src", url);
iFrame.setAttribute("style", "display:none;");
iFrame.setAttribute("height", "0px");
iFrame.setAttribute("width", "0px");
iFrame.setAttribute("frameborder", "0");
document.body.appendChild(iFrame);
// 发起请求后这个 iFrame 就没用了,所以把它从 dom 上移除掉
iFrame.parentNode.removeChild(iFrame);
iFrame = null;
}
function firstClick() {
loadURL("firstClick://shareClick?title=分享的标题&content=分享的内容&url=链接地址&imagePath=图片地址");
}
</script>
</header>
<body>
<h2> 这里是第一种方式 </h2>
<br/>
<br/>
<button type="button" οnclick="firstClick()">Click Me!</button>
</body>
</html>
OC端:
#pragma mark - UIWebViewDelegate
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
NSURL * url = [request URL];
if ([[url scheme] isEqualToString:@"firstclick"]) {
NSArray *params =[url.query componentsSeparatedByString:@"&"];
NSMutableDictionary *tempDic = [NSMutableDictionary dictionary];
for (NSString *paramStr in params) {
NSArray *dicArray = [paramStr componentsSeparatedByString:@"="];
if (dicArray.count > 1) {
NSString *decodeValue = [dicArray[1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
[tempDic setObject:decodeValue forKey:dicArray[0]];
}
}
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"方式一" message:@"这是OC原生的弹出窗" delegate:self cancelButtonTitle:@"收到" otherButtonTitles:nil];
[alertView show];
NSLog(@"tempDic:%@",tempDic);
return NO;
}
return YES;
}
注意:
1. JS中的firstClick,在拦截到的url scheme全都被转化为小写。
2.html中需要设置编码,否则中文参数可能会出现编码问题。
3.JS用打开一个iFrame的方式替代直接用document.location的方式,以避免多次请求,被替换覆盖的问题。
早期的JS与原生交互的开源库很多都是用得这种方式来实现的,例如:PhoneGap、WebViewJavascriptBridge。
实现方式2:借助JaveScriptCore库实现(推荐)
IOS 7之后,Apple添加了一个新的库JaveScriptCore,用来做JS 的交互,使JS和OC之间的交互变得简单了许多。
实现步骤:
(1)导入JaveScriptCore库,然后在OC中获取JS的上下文
JSContext *context = [self.webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
(2)定义JS要调用的方法,例:JS要调用goBack方法
则可以在UIWebView加载url完成后,在其代理方法中添加要调用的goBack方法:
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
[SVProgressHUD dismiss];
__weak typeof(self) weakSelf = self;
JSContext *context = [self.webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
context[@"goHisBack"] = ^() { // 后退
// NSArray *args = [JSContext currentArguments];
[weakSelf JSCallOCWithGoHisBack];
};
context[@"Jumpomment"] = ^() { // 跳转评论
NSArray *args = [JSContext currentArguments];
[weakSelf JSCallOCWithJumpomment:args];
};
context[@"openShare"] = ^() { // 打开分享
NSArray *args = [JSContext currentArguments];
[weakSelf JSCallOCWithOpenShare:args];
};
context[@"showAlert"] = ^() { // 点赞提示
NSArray *args = [JSContext currentArguments];
[weakSelf JSCallOCWithShowAlert:args];
};
}
- (void)JSCallOCWithGoHisBack
{
__weak typeof(self) weakSelf = self;
dispatch_async(dispatch_get_main_queue(), ^{
// 返回上一界面
[weakSelf.navigationController popViewControllerAnimated:YES];
});
}
- (void)JSCallOCWithJumpomment:(NSArray *)args
{
__weak typeof(self) weakSelf = self;
ZCYCommentDetailViewController *commentDVC = [[ZCYCommentDetailViewController alloc] init];
commentDVC.dataModel = self.dataModel;
dispatch_async(dispatch_get_main_queue(), ^{
[weakSelf.navigationController pushViewController:commentDVC animated:YES];
});
}
- (void)JSCallOCWithOpenShare:(NSArray *)args
{
dispatch_async(dispatch_get_main_queue(), ^{
// 打开分享面板
[ZCYShareTool showShareViewWithModel:self.dataModel];
});
}
- (void)JSCallOCWithShowAlert:(NSArray *)args
{
dispatch_async(dispatch_get_main_queue(), ^{
// 点赞提示
[MBProgressHUD showSuccess:[NSString stringWithFormat:@"%@",[args firstObject]]];
});
}
原文链接