UIWebView 与 js/html 之间交互

        UIWebView 与 js/html  之间交互主要是利用 UIWebView 中的   shouldStartLoadWithRequest 来与html 页面交互的. 当html 页面的 window.location.href 改变时都会执行该方法,所以当html 页面需要调用iOS原生方法只需要 设置一些特定的href 值即可. 如 href = “iOS:methodA” ,这样在 UIWebView 中  shouldStartLoadWithRequest 做出相应的处理并且返回 FALSE,不执行该请求,即页面不会跳转.
   在很多情况下都会用到这样的情况,如在一个webView 页面,如果用户没有登陆的话,那么需要转到原生态的iOS 登陆界面,也可以通过这种方法. 也可以直接把 href 直接加一个参数如: href = "http://xxx.com?method=login", 那么在 shouldStartLoadWithRequest   
里面只需要判断出对应的参数即可(记得一定要return FALSE,不然真的跳转了). 另一个情况就是在webView 里面打开app store里面的具体的某个应用.

用法如下:

html 页面:

<html>
   
<head>
       
<script type = "text/javascript" >
            btnClick =
function (){
                window.location.href=
"ios:openCamera" ;
            }
       
</script>
   
</head>
   
<body>
       
<br>
       
<br>
       
<input type = "button" onclick = "btnClick()" value = "open" >
   
</body>
</html>


创建webview

-( void )webViewTest{
   
UIWebView *webView = [[ UIWebView alloc ] init ];
   
NSURL *url = [ NSURL URLWithString : @"http://192.168.199.93/webview.html" ];
   
NSURLRequest *request = [[ NSURLRequest alloc ] initWithURL :url];
    webView.
frame = self . view . frame ;
    webView.
delegate = self ;
   
    [
self . view addSubview :webView];
    [webView
loadRequest :request];
   
}

webview 处理方法

-( BOOL )webView:( UIWebView *)webView shouldStartLoadWithRequest:( NSURLRequest *)request navigationType:( UIWebViewNavigationType )navigationType{
   
if ([request. URL . scheme isEqualToString : @"ios" ]) {
       
NSString *completeURL = request. URL . absoluteString ;
       
NSString *methodString = [completeURL substringFromIndex :[completeURL rangeOfString : @":" ]. location + 1 ];
       
       
SEL selector = NSSelectorFromString (methodString);
       
       
if ([ self respondsToSelector :selector]) {
            [
self performSelector :selector];
        }
       
return FALSE ;
    }
   
   
return YES ;
}

html页面需要执行的方法

-( void )openCamera{
   
NSLog ( @"open Camera!!" );
}

—完 2015年7月22日 上午11:28  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值