UIWebView复习

  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代码执行后的返回值传递给了客户端。

posted @ 2015-08-18 17:22  解忧杂货店  阅读(132)  评论(0编辑  收藏  举报