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裏面,發如今模擬器裏面是正常,而後再真機上加載不出來html
參考這篇文章 iOS Native加載H5中的圖片 github 源碼:https://github.com/CoderJackyHuang/iOSLoadWebViewImagegit
屢次嘗試,無果,找資料時發現下面的方法能夠加載沙盒中圖片github
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); }];