iOS WebView 加载本地资源(图片,文件等)
2017-07-06 12:17
369 查看
NSString *path = [[NSBundle mainBundle] pathForResource:@"关于.docx" ofType:nil]; NSURL *url = [NSURL fileURLWithPath:path]; NSLog(@"%@", [self mimeType:url]); //webview加载本地文件,可以使用加载数据的方式 //第一个诶参数是一个NSData, 本地文件对应的数据 //第二个参数是MIMEType //第三个参数是编码格式 //相对地址,一般加载本地文件不使用,可以在指定的baseURL中查找相关文件。 //以二进制数据的形式加载沙箱中的文件, NSData *data = [NSData dataWithContentsOfFile:path]; [self.webView loadData:data MIMEType:@"application/vnd.openxmlformats-officedocument.wordprocessingml.document" textEncodingName:@"UTF-8" baseURL:nil];
NSString *html; NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0]; NSString *htmlFilePath=[cachePath stringByAppendingPathComponent:@"123.html"]; // NSString *html=[[NSString alloc]initWithContentsOfFile:htmlFilePath encoding:NSUTF8StringEncoding error:nil]; NSURL *baseURL= [NSURL fileURLWithPath:htmlFilePath]; if ([[NSFileManager defaultManager] fileExistsAtPath:htmlFilePath]) { NSString *string = [NSString stringWithContentsOfFile:htmlFilePath encoding:NSUTF8StringEncoding error:nil]; if (string) { html = string; } } // NSString *path = [[NSBundle mainBundle] bundlePath]; // NSURL *baseURL2 = [NSURL fileURLWithPath:path]; [self.webView loadHTMLString:html baseURL:baseURL];
至于在沙盒里面的图片,想加载到web里面,发现在模拟器里面是正常,然后再真机上加载不出来
参考这篇文章 iOS Native加载H5中的图片 github 源码:https://github.com/CoderJackyHuang/iOSLoadWebViewImage
多次尝试,无果,找资料时发现下面的方法可以加载沙盒中图片
NSData *imageData=[NSData dataWithContentsOfFile:imagePath];//imagePath :沙盒图片路径 NSString *imageSource = [NSString stringWithFormat:@"data:image/jpg;base64,%@",[imageData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed]]; NSString *strJs=[NSString stringWithFormat:@"document.images[0].src='%@'",imageSource]; [webView evaluateJavaScript:strJs completionHandler:^(id _Nullable response, NSError * _Nullable error) { NSLog(@"webView response: %@ error: %@", response, error); }];
相关文章推荐
- iOS WebView 加载本地资源(图片,文件等)
- IOS开发(7)WKWebView加载本地HTML、CSS、JS文件JS(解决html内访问其他资源路径问题)
- Android - webview拦截css,js,图片后加载本地外部存储的文件(shouldOverrideUrlLoading)
- ios网络加载图片进行本地文件缓存开源插件sdwebimagecache
- Android Webview加载外部html时选择加载本地的js,css等资源文件
- IOS 使用 WKWebView 加载本地的JS和CSS文件出现乱码问题
- android WebView 控件加载本地sdcard中html文件图片的问题
- Android Webview 加载外部html时选择加载本地的js,css等资源文件
- IOS的WebView请求远程html并加载本地资源
- iOS webView加载本地html、css、js文件
- iOS webView 远端h5优先加载本地资源
- 关于webview 加载本地图片资源 显示不出来的解决办法
- iOS webView 远程html加载本地资源
- iOS webView加载本地html,及图片等问题
- android WebView 控件加载本地sdcard中html文件图片的问题
- iOS webView 远程html加载本地资源
- 关于webview 加载本地图片资源 显示不出来的解决办法
- android WebView加载html 并 引用本地资源(图片、字体库)
- Android Webview 加载外部html时选择加载本地的js,css等资源文件
- ios的webView加载本地html图片路径显示及webview适配