iOS-UIWebView的一些用法(js调oc方法)

  • UIWebView加载远程url
    NSURL *url = [NSURL URLWithString:@"[http://www.baidu.com]"];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [self.webView loadRequest:request];
  • UIWebView加载本地html

方法1

    //加载本地html
    NSString *basePath = [[NSBundle mainBundle] bundlePath];
    NSString *htmlPath = [basePath stringByAppendingPathComponent:@"test.html"];
    NSURL *url = [NSURL fileURLWithPath:htmlPath];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [self.webView loadRequest:request];

方法2

    NSString *path = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"html"];
    NSURL *url = [NSURL URLWithString:path];
    self.webView.scalesPageToFit = YES;
    NSString *htmlString = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
    [self.webView loadHTMLString:htmlString baseURL:url];
  • JS调用OC方法

网上有开源框架,可以实现native 和 js直接互相调用 WebViewJavascriptBridge,如果只是需要简单的调用的话,完全可以利用UIWebView的代理方法代替- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType,代码如下:

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    NSString *url = [[request URL] absoluteString];
//    NSURL *url = [request URL];
    
    NSLog(@"%@",url);
    //代码中根据返回的URL或者scheme来判断处理不同逻辑
    if ([url isEqualToString:@"demo://"])
    {
        DetailViewController *detail = [[DetailViewController alloc] init];
        [self.navigationController pushViewController:detail animated:YES];
    }
    return YES;
}

html代码如下:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
<title>
测试网页
</title>

<script type="text/javascript">
function demo()
{

<!--    alert(1212);-->
    window.location.href="demo://";
}
</script>

<style type="text/css">

/*div{

    border-radius: 30px;
    background-color: yellow;
    position: relative;
}*/
button{

    font-size: 40px;
    background-color: red;
    padding-top: 10px;
    margin: 30px;
    position: relative;
    left: 29%;
}

</style>
</head>

<body>
<div>
    </br></br></br></br></br></br></br>
<button onclick = "demo()" >按钮事件</button>
</div>

</body>
</html>

成长的路上总是会遇到...

                                           2015.6.30
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • OS之UIWebView的使用 刚接触IOS开发1年多,现在对于 混合式 移动端开发越来越流行,因为开发成本上、速...
    知之未道阅读 1,668评论 0 4
  • IOS之UIWebView的使用 刚接触IOS开发1年多,现在对于 混合式 移动端开发越来越流行,因为开发成本上、...
    学无止境666阅读 45,869评论 5 53
  • iOS开发系列--网络开发 概览 大部分应用程序都或多或少会牵扯到网络开发,例如说新浪微博、微信等,这些应用本身可...
    lichengjin阅读 3,721评论 2 7
  • http://www.cnblogs.com/mddblog/p/5281748.html 一、整体介绍 UIWe...
    F麦子阅读 1,261评论 0 2
  • 孕29w,我说,我想去婺源看油菜花。 你说,好的。 3.17,周五下班,你带上我,我们夜行近五百公里,去赴一场花的...
    王小姐要努力阅读 799评论 4 10