iOS开发 ☞ UIWebView

一、加载Xcode本地html

NSString* path = [[NSBundle mainBundle] pathForResource:@"File" ofType:@"html"]; NSURLRequest* request = [NSURLRequest requestWithURL:[NSURL fileURLWithPath:path]] ;
    [self.resuleWeb loadRequest:request];
<html>
    <head>
         <meta Charset = "UTF-8">
             <title>测试</title>
    </head>

    <body>
        Empty---> index.html
    </body>
</html>

二、OC调JS

//设置代理 遵守协议
 self.web.delegate = self;
- (void)webViewDidFinishLoad:(UIWebView *)webView { [webView stringByEvaluatingJavaScriptFromString:@"alert(document.title)"]; }

stringByEvaluatingJavaScriptFromString是有返回值的

Nsstring *htmlTitle = [webView stringByEvaluatingJavaScriptFromString:@"document.title"];

//调用函数

<html>
    <head>
         <meta Charset = "UTF-8">
         <title>测试</title>
         <script> function test() { return "测试函数"; } </script>
    </head>

    <body>
        Empty---> index.html
    </body>
</html>
- (void)webViewDidFinishLoad:(UIWebView *)webView {
  NSString *returnStr =  [webView stringByEvaluatingJavaScriptFromString:@"test()"];
    NSLog(@"%@",returnStr);
}

三、JS调OC

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    return YES;
}
                自定义协议      方法名
location.href = 'customName://doSomeThing';
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {

NSLog(@"%@",request.URL);
NSString *url = request.URL.absoluteString;
if([url hasPrefix:@"customName://"]){
[self doSomething];
return NO;
}
    return YES;
}

你可能感兴趣的:(html,ios开发)