webView 加载本地文件 - html/htm pdf docx tx
1 - (void)viewDidLoad 2 { 3 [super viewDidLoad]; 4 [self setupUI]; 5 6 NSString *path = [[NSBundle mainBundle] pathForResource:@"关于.docx" ofType:nil]; 7 NSURL *url = [NSURL fileURLWithPath:path]; 8 NSLog(@"%@", [self mimeType:url]); 9 10 11 //webview加载本地文件,可以使用加载数据的方式 12 //第一个诶参数是一个NSData, 本地文件对应的数据 13 //第二个参数是MIMEType 14 //第三个参数是编码格式 15 //相对地址,一般加载本地文件不使用,可以在指定的baseURL中查找相关文件。 16 17 //以二进制数据的形式加载沙箱中的文件, 18 NSData *data = [NSData dataWithContentsOfFile:path]; 19 20 [self.webView loadData:data MIMEType:@"application/vnd.openxmlformats-officedocument.wordprocessingml.document" textEncodingName:@"UTF-8" baseURL:nil]; 21 } 22 23 #pragma mark 加载docx文件 24 - (void)loadDOCX 25 { 26 27 NSString *path = [[NSBundle mainBundle] pathForResource:@"关于.docx" ofType:nil]; 28 NSURL *url = [NSURL fileURLWithPath:path]; 29 NSLog(@"%@", [self mimeType:url]); 30 31 NSData *data = [NSData dataWithContentsOfFile:path]; 32 33 [self.webView loadData:data MIMEType:@"application/vnd.openxmlformats-officedocument.wordprocessingml.document" textEncodingName:@"UTF-8" baseURL:nil];} 34 35 #pragma mark 加载pdf文件 36 - (void)loadPDF 37 { 38 NSString *path = [[NSBundle mainBundle] pathForResource:@"iOS6Cookbook.pdf" ofType:nil]; 39 NSURL *url = [NSURL fileURLWithPath:path]; 40 NSLog(@"%@", [self mimeType:url]); 41 42 NSData *data = [NSData dataWithContentsOfFile:path]; 43 44 [self.webView loadData:data MIMEType:@"application/pdf" textEncodingName:@"UTF-8" baseURL:nil]; 45 } 46 47 #pragma mark 加载本地文本文件 48 - (void)loadText 49 { 50 NSString *path = [[NSBundle mainBundle] pathForResource:@"关于.txt" ofType:nil]; 51 NSURL *url = [NSURL fileURLWithPath:path]; 52 NSLog(@"%@", [self mimeType:url]); 53 54 NSData *data = [NSData dataWithContentsOfFile:path]; 55 56 [self.webView loadData:data MIMEType:@"text/plain" textEncodingName:@"UTF-8" baseURL:nil]; 57 } 58 59 60 #pragma mark 加载本地html文件 61 - (void)loadHTML 62 { 63 NSString *path = [[NSBundle mainBundle] pathForResource:@"demo.html" ofType:nil]; 64 NSURL *url = [NSURL fileURLWithPath:path]; 65 NSLog(@"%@", [self mimeType:url]); 66 67 NSData *data = [NSData dataWithContentsOfFile:path]; 68 69 [self.webView loadData:data MIMEType:@"text/html" textEncodingName:@"UTF-8" baseURL:nil]; 70 } 71 72 73 #pragma mark 获取指定URL的MIMEType类型 74 - (NSString *)mimeType:(NSURL *)url 75 { 76 //1NSURLRequest 77 NSURLRequest *request = [NSURLRequest requestWithURL:url]; 78 //2NSURLConnection 79 80 //3 在NSURLResponse里,服务器告诉浏览器用什么方式打开文件。 81 82 //使用同步方法后去MIMEType 83 NSURLResponse *response = nil; 84 [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil]; 85 return response.MIMEType; 86 }