如何将本地HTML文件加载到UIWebView中?

时间:2011-01-10 09:45:34

标签: iphone ios uiwebview

我们如何将自己的html文件加载到UIWebView中?

7 个答案:

答案 0 :(得分:64)

以下代码将在项目文件夹中加载名为index.html的HTML文件:

[WebView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"]isDirectory:NO]]];

答案 1 :(得分:28)

Cody Gray是对的,但也有这样:

// Load the html as a string from the file system
NSString *path = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"];
NSString *html = [[NSString alloc] initWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];

// Tell the web view to load it
[WebView loadHTMLString:html baseURL:[[NSBundle mainBundle] bundleURL]];

如果您需要在加载之前编辑html,这非常有用。

答案 2 :(得分:6)

<强>夫特

    guard let path = NSBundle.mainBundle().pathForResource("index", ofType: "html") else {
        return
    }

    let url = NSURL(fileURLWithPath: path)
    self.webview.loadRequest(NSURLRequest(URL:url))

答案 3 :(得分:2)

通过使用以下代码,您可以在WebView.here web中加载html是Web视图obj和inde

Web.delegate = self;

[Web loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"]isDirectory:NO]]];

答案 4 :(得分:1)

Apple的文档建议使用loadHTMLString:baseURL:

  

使用loadHTMLString:baseURL:方法开始加载本地HTML文件或loadRequest:方法开始加载Web内容。使用stopLoading方法停止加载,使用loading属性查看Web视图是否正在加载。

loadHTMLString:baseURL:文档提供了进一步的推理:

  

为了帮助您避免受到安全攻击,请务必使用此方法加载本地HTML文件;不要使用loadRequest:。

这个可能会有所帮助:https://stackoverflow.com/a/29741277

答案 5 :(得分:0)

Swift版本2.1

// load html to String with Encoding
let path = NSBundle.mainBundle().pathForResource("policy", ofType: "html")
do {
    let fileHtml = try NSString(contentsOfFile: path!, encoding: NSUTF8StringEncoding)
    webView.loadHTMLString(fileHtml as String, baseURL: nil)
}
catch {

}

答案 6 :(得分:0)

NSString *htmlFile = [[NSBundle mainBundle] pathForResource:@"privacy-Policy" ofType:@"html" inDirectory:nil];
NSData *htmlData = [NSData dataWithContentsOfFile:htmlFile];
[webView loadData:htmlData MIMEType:@"text/html" textEncodingName:@"UTF-8" baseURL:[NSURL URLWithString:@""]];
相关问题