Shirish
Shirish

Reputation: 295

Edit and Load HTML from local file in Swift

I have a .html file stored in my project bundle. When I load it in WebView.(UIWebview/WKWebview) the data is loaded but the table structure in it isn't visible. The table borders, columns , rows. The values are just floating . In Chrome browser it opens properly.

let myURL = Bundle.main.url(forResource: "prescription", withExtension: "html")
    let myURLRequest:URLRequest = URLRequest(url: myURL!)
    webView.loadRequest(myURLRequest)

Chrome browser : This is how it looks in browser

iOS App UIWebView :

This is how it looks in UIWebview

The Html page is made responsive to fit in any sizes but I am not able to load in UIWebview properly as Web. I need to store the file locally because I need to make changes to its values and show on webview.

Upvotes: 2

Views: 5007

Answers (2)

Shirish
Shirish

Reputation: 295

Found the solution : If you are applying some local css whose path is there in HTML file. viz.

  1. Add that css file "myDefault.css" to your xcode project directory.
  2. Convert the HTML to string and replace the path of css in HTML file with your local path. :
  3. Load the content of HTML to UIWebView with base url. (Providing local file path as baseUrl is important)

    webView = UIWebView()
    
    let pathToInvoiceHTMLTemplate = Bundle.main.path(forResource: "presc", ofType: "html")
    let pathToHTMLCSS = Bundle.main.path(forResource: "myDefault", ofType: "css")
    do {
        var strHTMLContent = try String(contentsOfFile: pathToInvoiceHTMLTemplate!)
    
        strHTMLContent = strHTMLContent.replacingOccurrences(of: "./assets/stylesheets/myDefault.css", with: pathToHTMLCSS!)
    
    let pdfURL = URL(fileURLWithPath: pathToInvoiceHTMLTemplate!)
    webView.loadHTMLString(strHTMLContent, baseURL: pdfURL)
    
    }catch let err{
        print(err)
    }
    

Upvotes: 5

Andreas Oetjen
Andreas Oetjen

Reputation: 10199

When loading local content into the WKWebView, you shoudl use loadHTMLString(_:baseURL:) instead of loadRequest. The first function allows you to provide a base URL, which you will also let point into the bundle - so you clearly need to add all the relevant files to your application bundle.

guard let indexPath = Bundle.main.path(forResource: "index", ofType: "html"),
   let content =  try String(contentsOfFile: indexPath, encoding: .utf8),
   let baseUrl = URL(fileURLWithPath: indexPath) else {
        // Error handling
   }
webView.loadHTMLString(content, baseURL: baseUrl)

Upvotes: 0

Related Questions