Search code examples
iosuiwebview

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?


Solution

  • 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!