iOS开发--JS调用原生OC篇
2016-12-10 09:32
183 查看
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方法互相调用并传值(附HTML代码)
- iOS开发中JS调用原生方法并传值
- iOS开发-基于原生JS与OC方法互相调用并传值(附HTML代码)
- iOS开发-基于原生JS与OC方法互相调用并传值(附HTML代码)
- iOS与H5交互 H5与App原生交互,一般会是前端页面中的JavaScript与App使用的原生开发语言的交互。技术方案应能达到以下要求: 在js与原生进行交互的时候能保证正常的正向调用逻辑返回
- FB开源React Native,用JS开发原生iOS应用
- iOS下JS与原生OC互相调用
- iOS下JS与原生OC互相调用
- iOS开发-截获html按钮点击事件,实现js调用native代码
- iOS下JS与原生OC互相调用(精品)
- iOS下JS与原生OC互相调用(总结)
- JS调用Android、Ios原生控件_优就业
- IOS 与 Android WebView 中 JS 调用原生代码
- 安卓与html混合开发之原生与js相互调用
- phoneGap开发IOS,JS调用IOS方法/phoneGap插件开发
- iOS开发在js中调用oc可以实现在HTML5中调用手机系统的相册,拍照等。
- iOS下JS与原生OC互相调用
- iOS下JS与原生OC互相调用
- JS调用Android、Ios原生控件
- iOS下JS与原生OC互相调用(总结)