iOS WebView 加载本地资源(图片,文件等)
生活随笔
收集整理的這篇文章主要介紹了
iOS WebView 加载本地资源(图片,文件等)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
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:htmlFilePathencoding:NSUTF8StringEncodingerror: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);}];?
轉載于:https://www.cnblogs.com/dhui69/p/5596917.html
總結
以上是生活随笔為你收集整理的iOS WebView 加载本地资源(图片,文件等)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 将毫秒 换算成(天 时 分 秒 毫秒)
- 下一篇: 线程池的简单使用