经过UIWebView加载读取本地文件

经过UIWebView加载读取本地文件

      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];spa

    UIWebView *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相同)。

相关文章
相关标签/搜索