我想把本地的HTML文件加载到一个字符串变量中,但我不知道该如何做。请帮帮我。
我找到了下面的链接,但它是从在线URL加载的。
Swift和UIWebView元素隐藏
将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)
}
在 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)
我建议使用可选链代替上面的强制解包htmlString
。
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
}
简单回答
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)
}
}
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)
let htmlFile = Bundle.main.path(forResource: "default", ofType: "html")
。该文件也是编译包的一部分,并位于资源文件夹中。但当我尝试获取文件内容时,它会产生错误。我还尝试打印解包后的htmlFile的值,但返回了nil
…所以我的问题出在其他地方…您有任何想法我做错了什么吗? - Tomas Javureklet bundle = Bundle(for: MyView.self) let url = bundle.url(forResource:"default", withExtension:"html") let request = URLRequest(url: url!) self.webView.load(request)
- Tomas Javurek