打开本地文件推荐通过data的方式进行打开。
首先获取本地文件的路径:
NSString *path = [.........]//这里写你的文件路径,如果是沙盒目录中就去沙盒中拿
然后讲文件转为Data类型
NSData *Data = [NSData dataWithContentsOfFile:path];
在获取文件类型(一般文件名会带有后缀,可以通过后缀获取)
NSString *type = [path componentsSeparatedByString:@"."].lastObject;
获取到类型后,根据不同的类型对应不同的MIMEType,MINEType可以自行百度
if ([type isEqualToString:@"doc"] || [type isEqualToString:@"docx"]) {
[self.webView loadData:Data MIMEType:@"application/vnd.openxmlformats-officedocument.wordprocessingml.document" textEncodingName:@"UTF-8" baseURL:[NSURL fileURLWithPath:NSTemporaryDirectory()]];
}else if([type isEqualToString:@"txt"]){
[self.webView loadData:Data MIMEType:@"text/plain" textEncodingName:@"UTF-8" baseURL:[NSURL fileURLWithPath:NSTemporaryDirectory()]];
}else if([type isEqualToString:@"PDF"] || [type isEqualToString:@"pdf"]){
[self.webView loadData:Data MIMEType:@"application/pdf" textEncodingName:@"UTF-8" baseURL:[NSURL fileURLWithPath:NSTemporaryDirectory()]];
}else if([type isEqualToString:@"PNG"] || [type isEqualToString:@"png"]){
[self.webView loadData:Data MIMEType:@"image/png" textEncodingName:@"UTF-8" baseURL:[NSURL fileURLWithPath:NSTemporaryDirectory()]];
}else if([type isEqualToString:@"ppt"] || [type isEqualToString:@"pptx"]){
[self.webView loadData:Data MIMEType:@"application/vnd.ms-powerpoint" textEncodingName:@"UTF-8" baseURL:[NSURL fileURLWithPath:NSTemporaryDirectory()]];
}else{
[self.webView showMsg:@"暂不支持的文件类型"];//这行代码是用的MBProgressHUD的ShowMsg方法,可以自行替换。
}
网友评论