UIWebView是蘋果自帶的框架,也算是蘋果程序內部的瀏覽器,能夠瀏覽web網頁,也能夠打開HTML/HTM、PDF、docx、txt等格式的文本文件,其實蘋果自帶的瀏覽器Safari就是用UIWebView來實現的,具體原理簡單的說就是服務器將MIME的標識符等放入傳送的數據中,而後告訴瀏覽器使用哪一種插件來讀取相關對應的文件。html
1、UIWebView經過loadRequest方法加載各類本地文件web
實例展現:瀏覽器
(一)UIWebView經過loadRequest方法加載本地文件:服務器
一、首先把須要展現的文字放到word文檔裏面,而後保存文檔內容以後,把word文檔直接拖入到項目工程裏面;app
二、而後再須要展現word內容的控制器裏面,初始化一個webview,而後再用loadRequest方法加載word文檔便可。框架
(二)UIWebView經過loadRequest方法加載本地文件:測試
一、首先把word內容放到測試服務器上面,而後把連接複製出來;編碼
二、而後再須要展現word內容的控制器裏面,初始化一個webview,而後再用loadRequest方法加載word文檔便可。url
NSURL *url = [NSURL URLWithString:@"http://test.tea.com.cn:88/static/upload/使用說明.doc"];
[webView loadRequest:[NSURLRequest requestWithURL:url]];
webView.delegate = self;
NSData *data = [[NSData alloc] initWithContentsOfURL:url];spaUIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
[self.view addSubview:webView];
2、UIWebView經過loadData方法加載各類本地文件
一、加載docx文件:
NSString *path = [[NSBundle mainBundle] pathForResource:@"使用說明.docx" ofType:nil];
NSURL *url = [NSURL fileURLWithPath:path];
NSData *data = [NSData dataWithContentsOfFile:path];
[self.webView loadData:data MIMEType:@"application/vnd.openxmlformats-officedocument.wordprocessingml.document" textEncodingName:@"UTF-8" baseURL:nil];
二、加載pdf文件:
NSString *path = [[NSBundle mainBundle] pathForResource:@"使用說明.pdf" ofType:nil]; NSURL *url = [NSURL fileURLWithPath:path]; NSData *data = [NSData dataWithContentsOfFile:path]; [self.webView loadData:data MIMEType:@"application/pdf" textEncodingName:@"UTF-8" baseURL:nil];
三、加載txt文件:
NSString *path = [[NSBundle mainBundle] pathForResource:@"使用說明.txt" ofType:nil];
NSURL *url = [NSURL fileURLWithPath:path];
NSData *data = [NSData dataWithContentsOfFile:path];
[self.webView loadData:data MIMEType:@"text/plain" textEncodingName:@"UTF-8" baseURL:nil];
四、加載html文件:
NSString *path = [[NSBundle mainBundle] pathForResource:@"使用說明.html" ofType:nil];
NSURL *url = [NSURL fileURLWithPath:path];
NSData *data = [NSData dataWithContentsOfFile:path];
[self.webView loadData:data MIMEType:@"text/html" textEncodingName:@"UTF-8" baseURL:nil];
五、獲取指定URL的MIMEType類型
- (NSString *)mimeType:(NSURL *)url {
NSURLRequest *request = [NSURLRequest requestWithURL:url]; //2.NSURLConnection
//3.在NSURLResponse裏,服務器告訴瀏覽器用啥方式打開文件,使用同步方法後去MIMEType NSURLResponse *response = nil;
[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
return response.MIMEType;
3、總結
UIWebView加載內容的三種方式:1 、加載本地數據文件,指定文件的MIMEType,編碼格式使用@「UTF-8」 ;二、加載html字符串(能夠加載所有或者部分html文件);三、加載NSURLRequest文件(前兩步與NSURLConnect相同)。