码迷,mamicode.com
首页 > Web开发 > 详细

UIWebView复习

时间:2015-08-18 18:19:10      阅读:134      评论:0      收藏:0      [点我收藏+]

标签:

  UIWebView中网页和客户端方法互相调用很重要

  1.js调用oc

  网页部分

function testClick(cmd) 
{ 
    var str1="ios"; 
    window.location.href="ios://"+cmd+":/"+str1; 
}

<p><input type="button" id="enter" value="enter"onclick="testClick(‘update:‘);"/></p>
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    NSString *urlString = [[request URL] absoluteString];
    urlString = [urlString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSLog(@"urlString=%@",urlString);
    NSArray *urlComps = [urlString componentsSeparatedByString:@"://"];
    
    if([urlComps count] && [[urlComps objectAtIndex:0] isEqualToString:@"ios"])
    {
        NSArray *arrFucnameAndParameter = [(NSString*)[urlComps objectAtIndex:1] componentsSeparatedByString:@"/"];
        NSString *funcStr = [arrFucnameAndParameter objectAtIndex:0];
         if([funcStr isEqualToString:@"update"])
            {
                // 调用的方法,本地执行的代码
            }
        }
        return NO;
    }
    return YES;
}

  网页的按钮被点击了,通过window.location.href="ios://"+cmd+":/"+str1; 发送给浏览器,UIWebView获取到这句话,根据这句话里面的内容做事情。

  如果window.location.href="我要吃饭";,本地接收到这句话,判断有“我要吃饭”,然后就执行吃饭方法。说白了就是根据网页传过来的值,来执行不同方法。

 

  2.oc调用js

function postStr()
{
           return "javaScript返回值啦";
 }
-(IBAction)buttonClicked:(id)sender
{
    NSString *str = [self.webview     stringByEvaluatingJavaScriptFromString:@"postStr();"];
    NSLog(@"JS返回值:%@",str);
}

  点击了本地的buttonClicked按钮后,就能调用网页的js代码。把js代码执行后的返回值传递给了客户端。

UIWebView复习

标签:

原文地址:http://www.cnblogs.com/ylzx/p/4740025.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!