星空网 > 软件开发 > 操作系统

OC与JS的交互

现在APP的开发已经不局限于原生开发,很多都是原生+html5这种混合开发

我们可以通过webView这个控件,实现混合开发。

1.首先你需要创建一个html页面

<html>  <head>    <meta charset="utf-8">    <title>第一个页面</title>  </head>    <script>    function login() {      location.href = 'ddz://call_?200';    }  </script>    <body>    <button style="background: blue; width:100px; height:30px" onclick="login()">确定</button>    <br>    <a href="http://www.baidu.com">百度</a>  </body></html>

在app初始化时,加载这个页面

- (void)viewDidLoad {  [super viewDidLoad];    [self.webView loadRequest:[NSURLRequest requestWithURL:[[NSBundle mainBundle] URLForResource:@"index" withExtension:@"html"]]];}

2.实现UIWebViewDelegate这个协议

利用stringByEvaluationgJavaScriptFromString这个协议方法,

可以完成OC调用JS

#pragma mark - <UIWebViewDelegate>- (void)webViewDidFinishLoad:(UIWebView *)webView {  [webView stringByEvaluatingJavaScriptFromString:@"alert(100)"];}

3.

利用shouldStartLoadWithRequest这个方法可以完成JS调用OC

/** * 通过这个方法完成JS调用OC * 第三方框架 :WebViewJavaScriptBridge */- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {  //url = ddz://sendMessage_?200  NSString *url = request.URL.absoluteString;  NSString *scheme = @"ddz://";  if ([url hasPrefix:@"ddz://"]) {    NSLog(@"调用OC的方法");        //获得协议后面的路径 path = sendMessage_?200    NSString *path = [url substringFromIndex:scheme.length];    //利用?进行切割    NSArray *subpaths = [path componentsSeparatedByString:@"?"];    //方法名 methodName = sendMessage:    NSString *methodName = [[subpaths firstObject] stringByReplacingOccurrencesOfString:@"_" withString:@":"];    //参数 params = 200    NSString *params = [subpaths lastObject];        [self performSelector:NSSelectorFromString(methodName) withObject:params];//    NSLog(@"%@",subpaths);    return NO;  }    NSLog(@"想加载其他请求,不是想调用OC的方法");    return YES;}

4.

在github上也找到了一个 oc 和 js 之间能够交互的类,可以看一下 https://github.com/marcuswestin/WebViewJavascriptBridge




原标题:OC与JS的交互

关键词:JS

JS
*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。

tiktok精选联盟入口:https://www.goluckyvip.com/tag/81963.html
tiktok正版:https://www.goluckyvip.com/tag/81964.html
mihye在tiktok叫什么:https://www.goluckyvip.com/tag/81965.html
tiktok 听证会:https://www.goluckyvip.com/tag/81966.html
tiktok vps:https://www.goluckyvip.com/tag/81967.html
怎么下载tiktok视频:https://www.goluckyvip.com/tag/81968.html
长治婚庆女司仪和主持人:https://www.vstour.cn/a/366176.html
北京丰台区水上乐园哪家好玩?:https://www.vstour.cn/a/366177.html
相关文章
我的浏览记录
最新相关资讯
海外公司注册 | 跨境电商服务平台 | 深圳旅行社 | 东南亚物流