一、概念
UIWebView是用来加载html文件、网址、本地文件等的框架。
二、使用方法
0.初始化UIWebView
可以用storyboard初始化,也可以代码初始化。
if
(!
_webView
) {
CGRect frame = [ UIScreen mainScreen].bounds;
_webView = [[UIWebViewalloc]initWithFrame:frame];
//识别webView中的类型,如有电话号码,点击直接可拨打
_webView.dataDetectorTypes =UIDataDetectorTypeAll;
_webView.delegate =self;
_webView.scalesPageToFit =YES;
[self.viewaddSubview:_webView];
CGRect frame = [ UIScreen mainScreen].bounds;
_webView = [[UIWebViewalloc]initWithFrame:frame];
//识别webView中的类型,如有电话号码,点击直接可拨打
_webView.dataDetectorTypes =UIDataDetectorTypeAll;
_webView.delegate =self;
_webView.scalesPageToFit =YES;
[self.viewaddSubview:_webView];
}
初始化UIWebView时,_
webView.dataDetectorTypes = UIDataDetectorTypeAll;
是识别webview中的类型,例如 当webview中有电话号码,点击号码就能直接打电话。
1.加载网页
NSURL
* url = [
NSURL
URLWithString:urlStr];
NSURLRequest * request = [NSURLRequestrequestWithURL:url];
NSURLRequest * request = [NSURLRequestrequestWithURL:url];
[_webViewloadRequest:request];
2.加载本地html文件(可加载image)
//baseURL
把项目根目录统一中项目下,加载
double.html
中的
image, css
的话,不需要写路径,直接写名字就可以。这样
html
中的图片就可以正常显示了
NSURL * baseURL = [ NSURL fileURLWithPath:[NSBundlemainBundle].bundlePath];
NSString * htmlPath = [[NSBundlemainBundle]pathForResource:@"double"ofType:@"html"];
NSURL * baseURL = [ NSURL fileURLWithPath:[NSBundlemainBundle].bundlePath];
NSString * htmlPath = [[NSBundlemainBundle]pathForResource:@"double"ofType:@"html"];
NSString * htmlCont = [NSStringstringWithContentsOfFile:htmlPathencoding:NSUTF8StringEncodingerror:nil];
[_webViewloadHTMLString:htmlContbaseURL:baseURL];
3.加载加载本地或者从服务器下载的文件,如txt,pdf,word等
//
获取本地文件的
url
NSURL * fileURL = [[ NSBundle mainBundle]URLForResource:@"LocalFile.txt"withExtension:nil];
NSURLRequest * request = [NSURLRequestrequestWithURL:fileURL];
NSURL * fileURL = [[ NSBundle mainBundle]URLForResource:@"LocalFile.txt"withExtension:nil];
NSURLRequest * request = [NSURLRequestrequestWithURL:fileURL];
[_webViewloadRequest:request];