標籤:
-
源: http://www.jianshu.com/p/c38a8a8edcf0
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>
iOS-UIWebView的一些用法(js調oc方法)