i want to load my local html file into a string variable. i don't know how to do it. please help me. i found below link but it load it from online url. Swift & UIWebView element to hide
Copy the html into your project directory and use this code :
@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)
}
You can write some utility method like this and get the html string and load it to webview. I used the URL approach here
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
}
In 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)
I recommend using optional chaining instead of force unwrapping htmlString
as above.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With