您的位置:首页 > 移动开发 > WebAPP

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

2015-01-04 16:52 453 查看
实现功能:点击HTML的标签,通过JS调用iOS内部的原生函数

基本流程:



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

Web中的HTML代码:

view
sourceprint?

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的原生代码:

view
sourceprint?

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐