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代码如下:




    

测试网页















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

                                           2015.6.30

你可能感兴趣的:(iOS-UIWebView的一些用法(js调oc方法))