UIWebView是IOS内置的浏览器,可以浏览网页,打开文档 html/htm pdf docx txt等格式的文件。 safari浏览器就是通过UIWebView做的。
服务器将MIME的标识符等放入传送的数据中告诉浏览器使用那种插件读取相关文件。
uiwebview加载各种本地文件(通过loadData方法):
- - (void)viewDidLoad
- {
- [super viewDidLoad];
- [self setupUI];
-
- NSString *path = [[NSBundle mainBundle] pathForResource:@"关于.docx" ofType:nil];
- NSURL *url = [NSURL fileURLWithPath:path];
- NSLog(@"%@", [self mimeType:url]);
-
-
-
-
-
-
-
-
-
- NSData *data = [NSData dataWithContentsOfFile:path];
-
- [self.webView loadData:data MIMEType:@"application/vnd.openxmlformats-officedocument.wordprocessingml.document" textEncodingName:@"UTF-8" baseURL:nil];
- }
-
- #pragma mark 加载docx文件
- - (void)loadDOCX
- {
-
- NSString *path = [[NSBundle mainBundle] pathForResource:@"关于.docx" ofType:nil];
- NSURL *url = [NSURL fileURLWithPath:path];
- NSLog(@"%@", [self mimeType:url]);
-
- NSData *data = [NSData dataWithContentsOfFile:path];
-
- [self.webView loadData:data MIMEType:@"application/vnd.openxmlformats-officedocument.wordprocessingml.document" textEncodingName:@"UTF-8" baseURL:nil];}
-
- #pragma mark 加载pdf文件
- - (void)loadPDF
- {
- NSString *path = [[NSBundle mainBundle] pathForResource:@"iOS6Cookbook.pdf" ofType:nil];
- NSURL *url = [NSURL fileURLWithPath:path];
- NSLog(@"%@", [self mimeType:url]);
-
- NSData *data = [NSData dataWithContentsOfFile:path];
-
- [self.webView loadData:data MIMEType:@"application/pdf" textEncodingName:@"UTF-8" baseURL:nil];
- }
-
- #pragma mark 加载本地文本文件
- - (void)loadText
- {
- NSString *path = [[NSBundle mainBundle] pathForResource:@"关于.txt" ofType:nil];
- NSURL *url = [NSURL fileURLWithPath:path];
- NSLog(@"%@", [self mimeType:url]);
-
- NSData *data = [NSData dataWithContentsOfFile:path];
-
- [self.webView loadData:data MIMEType:@"text/plain" textEncodingName:@"UTF-8" baseURL:nil];
- }
-
-
- #pragma mark 加载本地html文件
- - (void)loadHTML
- {
- NSString *path = [[NSBundle mainBundle] pathForResource:@"demo.html" ofType:nil];
- NSURL *url = [NSURL fileURLWithPath:path];
- NSLog(@"%@", [self mimeType:url]);
-
- NSData *data = [NSData dataWithContentsOfFile:path];
-
- [self.webView loadData:data MIMEType:@"text/html" textEncodingName:@"UTF-8" baseURL:nil];
- }
-
-
- #pragma mark 获取指定URL的MIMEType类型
- - (NSString *)mimeType:(NSURL *)url
- {
-
- NSURLRequest *request = [NSURLRequest requestWithURL:url];
-
-
-
-
-
- NSURLResponse *response = nil;
- [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
- return response.MIMEType;
- }
uiwebview加载各种本地文件(通过loadRequest方法):
- - (void)viewDidLoad
- {
- [super viewDidLoad];
- [self setupUI];
-
-
-
-
- NSURL *url = [[NSBundle mainBundle] URLForResource:@"iOS6Cookbook.pdf" withExtension:nil];
-
-
- NSURLRequest *request = [NSURLRequest requestWithURL:url];
- [self.webView loadRequest:request];
-
-
-
-
-
-
-
-
-
- }
UIWebView加载内容的三种方式:
1 加载本地数据文件
指定文件的MIMEType
编码格式使用@“UTF-8”
2加载html字符串(可以加载全部或者部分html文件)
3加载NSURLRequest文件(前两步与NSURLConnect相同)