我想将本地html文件加载到字符串变量中。我不知道该怎么做。请帮我。 我发现下面的链接,但它从在线网址加载它。 Swift & UIWebView element to hide
答案 0 :(得分:13)
将html复制到项目目录中并使用以下代码:
@IBOutlet weak var webView: UIWebView!
override func viewDidLoad() {
super.viewDidLoad()
var htmlFile = NSBundle.mainBundle().pathForResource("MyHtmlFile", ofType: "html")
var htmlString = try? String(contentsOfFile: htmlFile!, encoding: NSUTF8StringEncoding)
webView.loadHTMLString(htmlString!, baseURL: nil)
}
答案 1 :(得分:6)
在Swift 3中:
let htmlFile = Bundle.main.path(forResource:"MyHtmlFile", ofType: "html")
let htmlString = try? String(contentsOfFile: htmlFile!, encoding: String.Encoding.utf8)
webView.loadHTMLString(htmlString!, baseURL: nil)
我建议使用optional chaining而不是如上所述强行展开htmlString
。
答案 2 :(得分:0)
您可以编写一些这样的实用方法并获取html字符串并将其加载到webview。我在这里使用了URL方法
private func getHTML() -> String {
var html = ""
if let htmlPathURL = Bundle.main.url(forResource: "test", withExtension: "html"){
do {
html = try String(contentsOf: htmlPathURL, encoding: .utf8)
} catch {
print("Unable to get the file.")
}
}
return html
}
答案 3 :(得分:0)
Swift 3语法:
guard
let file = Bundle.main.path(forResource: "agreement", ofType: "html"),
let html = try? String(contentsOfFile: file, encoding: String.Encoding.utf8)
else {
return
}
webView.loadHTMLString(html, baseURL: nil)
答案 4 :(得分:0)
简单回答
let indexPath = Bundle.main.path(forResource: "index", ofType: "html", inDirectory: "/")
if let indexPath = indexPath
{
do
{
let htmlContent = try String(contentsOfFile: indexPath, encoding: String.Encoding.utf8)
let base = Bundle.main.resourceURL
self.webView.loadHTMLString(htmlContent, baseURL: base)
}
catch let err as NSError
{
print(err.debugDescription)
}
}