BraveEvidence
BraveEvidence

Reputation: 85

WebView not showing my html file

I have a webView in my ViewController. I have created a BullsEye.html file in my project and I want to show that html file in my web view. Following is my code

if let url = Bundle.main.url(forResource: "BullsEye",
                                 withExtension: "html") {
      if let htmlData = try? Data(contentsOf: url) {
        let baseURL = URL(fileURLWithPath: Bundle.main.bundlePath)
        webView.load(htmlData, mimeType: "text/html",
                     textEncodingName: "UTF-8", baseURL: baseURL)
      }
    }

The above code is written in viewDidLoad. What am I missing?

Upvotes: 0

Views: 1082

Answers (3)

Kazunori Takaishi
Kazunori Takaishi

Reputation: 2388

There is no problem with your source code itself, I think.

But maybe does Bundle.main.url(forResource: "BullsEye", withExtension: "html") return nil? If so, you should check for the two things below:

  1. Whether the file to be read is included in Copy Bundle Resources

    Files to be included in the project are registered in TARGETS> Build Phases> Copy Bundle Resources.

enter image description here

  1. Whether the file to be read exists in the project directory

    Open the project directory in the Finder and check if the file you are trying to load actually exists.

enter image description here

Hope this helps!

Upvotes: 1

CodeBender
CodeBender

Reputation: 36610

I ran your code as is and was able to make things work as seen here after changing the webView loader code. This tells me you likely have a UIWebView lurking somewhere, likely your view in storyboard.

enter image description here

I would recommend you make sure that you are consistently using WKWebView throughout:

  • Import WebKit in your class file
  • Have a valid output link to it if you are using a storyboard
  • If using a storyboard, ensure that you are using WKWebView and not the deprecated UIWebView

enter image description here

Upvotes: 2

Maulik Bhuptani
Maulik Bhuptani

Reputation: 616

Below code will help you.

   func loadHtmlFile() {
        if let fileurl = Bundle.main.url(forResource: "BullsEye", withExtension: "html") {  
            let request = URLRequest(url: fileurl!)
            webView.loadRequest(request)
    }
}

See - swiftdeveloperblog

Also if the code don't seem to work for you, make sure to open html file in any browser and check if it's a valid html file.

Upvotes: 0

Related Questions