iOS在WebApp中如何使用JS调用iOS的函数

实现功能:点击HTML的标签,通过JS调用iOS内部的原生函数


基本流程:

\


先看一下Web中,我们给h3标签添加一个onclick事件,让它在被点击之后,修改当前的url。

Web中的HTML代码:

01. <html>
02. <head>
03. <script>
04.  
05. function getInfo(name)
06. {
07. window.location = "/getInfo/"+name;
08. }
09.  
10.  
11. </script>
12.  
13. </head>
14.  
15. <body>
16. <h3 onclick="getInfo('why')">Name</h3>
17. </body>
18.  
19. </html>



iOS中,先拖拽WebView,访问localhost,然后通过WebView的委托事件监听url跳转操作,并且把跳转截取下来。

也就是说,在onclick的时候,普通浏览器灰跳转到那个url,但是在iOS的这个WebView里面,这个跳转会被拦截,

用这种方式可以巧妙地实现JS调用iOS的原生代码:


01. //
02. //  DWViewController.m
03. //  DareWayApp
04. //
05. //  Created by why on 14-6-3.
06. //  Copyright (c) 2014年 DareWay. All rights reserved.
07. //
08.  
09. #import "DWViewController.h"
10.  
11. @interface DWViewController ()
12.  
13. @property (weak, nonatomic) IBOutlet UIWebView *myWebview;  // 主页面
14.  
15. @end
16.  
17. @implementation DWViewController
18.  
19. - (void)viewDidLoad
20. {
21. [super viewDidLoad];
22. // Do any additional setup after loading the view, typically from a nib.
23.  
24.  
25.  
26. // 适配iOS6的状态栏
27. if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7) {
28. _myWebview.frame =  CGRectMake(0,20,self.view.frame.size.width,self.view.frame.size.height-20);
29. }
30.  
31.  
32. // 加载制定的URL
33. NSURL *url =[NSURL URLWithString:@"http://localhost"];
34. NSURLRequest *request =[NSURLRequest requestWithURL:url];
35. [_myWebview setDelegate:self];
36. [_myWebview loadRequest:request];
37.  
38. }
39.  
40. // 网页中的每一个请求都会被触发
41. -(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
42. {
43.  
44. // 每次跳转时候判断URL
45.  
46. if([request.mainDocumentURL.relativePath isEqualToString:@"/getInfo/why"])
47. {
48. NSLog(@"why");
49. return NO;
50. }
51.  
52.  
53. return YES;
54. }
55.  
56. - (void)didReceiveMemoryWarning
57. {
58. [super didReceiveMemoryWarning];
59. // Dispose of any resources that can be recreated.
60. }
61.  
62. @end
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值