Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to load local html file to string variable in ios swift?

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

like image 439
ibad ur rahman Avatar asked Oct 22 '15 06:10

ibad ur rahman


3 Answers

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)


}
like image 168
Rizwan Shaikh Avatar answered Nov 06 '22 23:11

Rizwan Shaikh


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
    }
like image 35
anoop4real Avatar answered Nov 06 '22 22:11

anoop4real


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.

like image 6
askielboe Avatar answered Nov 06 '22 21:11

askielboe