1

While working on a web app for weeks, I used a external URL in my (WKWebView) web view. Now I'm moving towards production I want to embed the webapp and load a local webpage.

I simply moved from

let url = URL(string: "http://hidden-url.com/")
self.webView!.load(URLRequest(url: url!))

To

let url = URL(string: Bundle.main.path(forResource: "index_prod", ofType: "html")!)
self.webView!.load(URLRequest(url: url!))

But this causes my app to crash. I'm sure the file is loaded correctly and a print before, in-between and after the lines will appear in the console.

The error: Thread 1: EXC_BAD_ACCESS (code=1, address=0x10)

rmaddy
  • 307,833
  • 40
  • 508
  • 550
Jeffrey Lanters
  • 605
  • 5
  • 15
  • check whether you added index_prod file into the target – Vinodh Dec 04 '17 at 13:00
  • I double checked it, it's listed in my project hierarchy and at 'Copy Bundle Resources' in the Build Phases – Jeffrey Lanters Dec 04 '17 at 13:03
  • surround with try catch to get exception – Vinodh Dec 04 '17 at 13:05
  • Loading the file does not catch any exceptions, loading it into the web view will. – Jeffrey Lanters Dec 04 '17 at 13:13
  • 1
    https://stackoverflow.com/questions/24882834/wkwebview-not-loading-local-files-under-ios-8 https://stackoverflow.com/questions/39336235/wkwebview-does-load-resources-from-local-document-folder You either have to use `loadHTMLString()` or `loadFileURL(url:allowingReadAccessTo:)`. – Larme Dec 04 '17 at 15:56
  • @Larme true, but that question is about Objective-C mine is about Swift. – Jeffrey Lanters Dec 04 '17 at 16:32
  • @JeffreyLanters Both of my linked question have Swift code. Both explain WHY your code doesn't work and why you need to use a different approach. They may not be Swift 4 compliant, but the explanation in itself should be enough. – Larme Dec 04 '17 at 16:41

1 Answers1

1

You need to load the string content from the file, use contentsOfFile method to get the string and use loadHTMLString method of webview, print the error or create some enum which shows the error

enum WebError: Swift.Error {
    case fileNotFound(name: String)
    case parsing(contentsOfFile: String)
}

guard let url = Bundle.main.path(forResource: "index_prod", ofType: "html") else {
   throw WebError.fileNotFound(name: file) // throw file not found error 
}

do {
      let html = try String(contentsOfFile: url)
      self.webView.loadHTMLString(html, baseURL: Bundle.main.bundleURL)
} catch {
      throw WebError.parsingError(contentsOfFile: file) 
}
Suhit Patil
  • 11,156
  • 3
  • 46
  • 58