How to load local html file into string variable in ios swift?

I want to load a local html file into a string variable. I do not know how to do that. please, help. I found the link below, but downloaded it from the online url. Swift element and UIWebView to hide

+4
source share
4 answers

Copy html to the 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)


}
+10
source

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 an optional chain instead of deploying power htmlString, as described above.

+6
source

, , 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
    }
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)
0

Source: https://habr.com/ru/post/1612693/


All Articles