iOS开发--JS调用原生OC篇
JS调用原生OC篇
方式一(反正我不用)
第一种方式是用JS发起一个假的URL请求,然后利用UIWebView的代理方法拦截这次请求,然后再做相应的处理。
我写了一个简单的HTML网页和一个btn点击事件用来与原生OC交互,HTML代码如下:
<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" onclick="firstClick()">Click Me!</button>
</body>
</html>
然后在项目的控制器中实现UIWebView的代理方法:
#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。关于这种方式调用OC方法,唐巧早期有篇文章有过介绍:
关于UIWebView和PhoneGap的总结
方式二(自己用的这种)
在iOS 7之后,apple添加了一个新的库JavaScriptCore
,用来做JS交互,因此JS与原生OC交互也变得简单了许多。
- 首先导入JavaScriptCore库, 然后在OC中获取JS的上下文
JSContext *context = [self.webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
- 再然后定义好JS需要调用的方法,例如JS要调用share方法:
则可以在UIWebView加载url完成后,在其代理方法中添加要调用的share方法:
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
JSContext *context = [self.webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
//定义好JS要调用的方法, share就是调用的share方法名
context[@"share"] = ^() {
NSLog(@"+++++++Begin Log+++++++");
NSArray *args = [JSContext currentArguments];
dispatch_async(dispatch_get_main_queue(), ^{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"方式二" message:@"这是OC原生的弹出窗" delegate:self cancelButtonTitle:@"收到" otherButtonTitles:nil];
[alertView show];
});
for (JSValue *jsVal in args) {
NSLog(@"%@", jsVal.toString);
}
NSLog(@"-------End Log-------");
};
}
注意:
可能最新版本的iOS系统做了改动,现在(iOS9,Xcode 7.3,去年使用Xcode 6 和iOS 8没有线程问题)中测试,block中是在子线程,因此执行UI操作,控制台有警告,需要回到主线程再操作UI。
项目中自己的代码
- (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]]];
});
}
iOS开发--JS调用原生OC篇的更多相关文章
- iOS下JS与原生OC互相调用(总结)
这是去年总结的一篇文章,也一并先放到这个目录下好了. iOS开发免不了要与UIWebView打交道,然后就要涉及到JS与原生OC交互,今天总结一下JS与原生OC交互的两种方式. JS调用原生OC篇 方 ...
- iOS开发——高级技术精选OC篇&Runtime之字典转模型实战
Runtime之字典转模型实战 如果您还不知道什么是runtime,那么请先看看这几篇文章: http://www.cnblogs.com/iCocos/p/4734687.html http://w ...
- iOS开发——网络使用技术OC篇&网络爬虫-使用正则表达式抓取网络数据
网络爬虫-使用正则表达式抓取网络数据 关于网络数据抓取不仅仅在iOS开发中有,其他开发中也有,也叫网络爬虫,大致分为两种方式实现 1:正则表达 2:利用其他语言的工具包:java/Python 先来看 ...
- ios开发——常用经典算法OC篇&冒泡/快速
冒泡排序与快速排序 1.序言 ios开发中涉及到算法的地方还真不多,除非你的应用程序真的非常大,或者你想你的应用程序性能非常好才会去想到关于算法方面的性能优化,而在ios开发中真的能用得到的也就是关于 ...
- iOS开发——高级UI之OC篇&UIdatePicker&UIPickerView简单使用
UIdatePicker&UIPickerView简单使用 /***************************************************************** ...
- iOS下JS与原生的交互一
本篇主要讲的是UIWebView和JS的交互,在下一节会有wkWebView和JS交互的详解https://www.cnblogs.com/llhlj/p/9144110.html JS调用原生OC ...
- JS与原生OC/Swift相互调用总结
代码地址如下:http://www.demodashi.com/demo/12754.html JS-OC-Swift JS和OC/Swift相互调用,主要总结了JS和OC交互的三种方式 1.使用UI ...
- IOS 开发,调用打电话,发短信,打开网址
IOS 开发,调用打电话,发短信,打开网址 1.调用 自带mail [[UIApplication sharedApplication] openURL:[NSURL URLWithString: ...
- iOS开发--混编篇&swift与OC混合使用
Swift与OC混合使用 swift 语言出来后,可能新的项目直接使用swift来开发,但可能在过程中会遇到一些情况,某些已用OC写好的类或封装好的模块,不想再在swift 中再写一次,哪就使用混编. ...
随机推荐
- Win10 UWP系列:关于错误 0x80073CF9及一个小bug的解决
最近一直在开发XX的uwp版本,也是边摸索边做,最近遇到几个比较奇怪的问题,记录于此. 1.项目可用部署到PC,但无法部署到手机,提示以下错误: 错误 : DEP0001 : 意外错误: Instal ...
- FunDA(2)- Streaming Data Operation:流式数据操作
在上一集的讨论里我们介绍并实现了强类型返回结果行.使用强类型主要的目的是当我们把后端数据库SQL批次操作搬到内存里转变成数据流式按行操作时能更方便.准确.高效地选定数据字段.在上集讨论示范里我们用集合 ...
- spring源码:web容器启动(li)
web项目中可以集成spring的ApplicationContext进行bean的管理,这样使用起来bean更加便捷,能够利用到很多spring的特性.我们比较常用的web容器有jetty,tomc ...
- Java之多态(一)
package test05; public class DuoTai_Test { /** * 一个对象,多种形态 * WQQ → Student.Worker.Friend 1).一个对象,多种形 ...
- javascript实现键盘自动打字效果
最近在网上看到一个字符逐个出现的打字效果,觉得挺有趣的,想一想基本实现思路就是设置一个定时器逐然后逐个向容器中添加字符,于是就基于jQuery写了一个简单版的. <!DOCTYPE html&g ...
- Ubantu【第一篇】:Ubantu中openssh连接
h3 { color: rgb(255, 255, 255); background-color: rgb(30,144,255); padding: 3px; margin: 10px 0px } ...
- 【转】漫谈iOS程序的证书和签名机制
转自:漫谈iOS程序的证书和签名机制 接触iOS开发半年,曾经也被这个主题坑的摸不着头脑,也在淘宝上买过企业证书签名这些服务,有大神都做了一个全自动的发布打包(不过此大神现在不卖企业证书了),甚是羡慕 ...
- 微信Swift完整项目应用源码
TSWeChat 中文说明 A WeChat alternative, written in Swift. 运行环境 Cocoapods 0.39.0 + iOS 8.0+ / Mac OS X 10 ...
- docker通过iptables修改或新增镜像映射端口
443 8088 22 端口是初始映射端口 [root@SERVER ~]# docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAM ...
- CentOS安装SVN服务器
Step1:安装svn服务器 $ yum install subversion Step2:创建SVN版本库目录 $ mkdir /workplace/svnrepos Step3:创建版本库 $ s ...