我正在尝试将 html 文件加载到我的 UIWebView 中,但它不起作用。这是阶段:我的项目中有一个名为 html_files 的文件夹。然后我在界面生成器中创建了一个 webView,并在 viewController 中为其分配了一个 socket 。这是我用来附加 html 文件的代码:
-(void)viewDidLoad
{
NSString *htmlFile = [[NSBundle mainBundle] pathForResource:@"sample" ofType:@"html" inDirectory:@"html_files"];
NSData *htmlData = [NSData dataWithContentsOfFile:htmlFile];
[webView loadData:htmlData MIMEType:@"text/html" textEncodingName:@"UTF-8" baseURL:[NSURL URLWithString:@""]];
[super viewDidLoad];
}
这不起作用,UIWebView 是空白的。我将不胜感激。
最佳答案
可能最好使用 NSString 并按如下方式加载 html 文档:
Objective-C
NSString *htmlFile = [[NSBundle mainBundle] pathForResource:@"sample" ofType:@"html"];
NSString* htmlString = [NSString stringWithContentsOfFile:htmlFile encoding:NSUTF8StringEncoding error:nil];
[webView loadHTMLString:htmlString baseURL: [[NSBundle mainBundle] bundleURL]];
swift
let htmlFile = NSBundle.mainBundle().pathForResource("fileName", ofType: "html")
let html = try? String(contentsOfFile: htmlFile!, encoding: NSUTF8StringEncoding)
webView.loadHTMLString(html!, baseURL: nil)
Swift 3 有一些变化:
let htmlFile = Bundle.main.path(forResource: "intro", ofType: "html")
let html = try? String(contentsOfFile: htmlFile!, encoding: String.Encoding.utf8)
webView.loadHTMLString(html!, baseURL: nil)
你试过了吗?
还要检查 pathForResource:ofType:inDirectory
调用是否找到了资源。
关于ios - 如何将本地 html 文件加载到 UIWebView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7063276/