What's the difference between UIWebView and WKWebView when loading local resources

Rufus picture Rufus · Dec 14, 2016 · Viewed 34.6k times · Source

I want to load local resources with webView. I built a demo with both UIWebView and WKWebView to do some test with the code below.

    let uiWebView = UIWebView(frame: self.view.bounds)
    self.view.addSubview(uiWebView)

    let wkWebView = WKWebView(frame:CGRect(x: 0, y: 400, width: 500, height: 500))
    self.view.addSubview(wkWebView)

    let path = Bundle.main.path(forResource:"1", ofType: "png")

    guard let realPath = path else {
        return
    }

    let url = URL(string: realPath)
    let fileUrl = URL(fileURLWithPath: realPath)

    if let realUrl = url {
        uiWebView.loadRequest(URLRequest(url:realUrl))
        wkWebView.load(URLRequest(url:realUrl))
    }


  // uiWebView.loadRequest(URLRequest(url:fileUrl))
  // wkWebView.load(URLRequest(url:fileUrl))

The uiWebView can load the resource but wkWebView can not. But if I use

  uiWebView.loadRequest(URLRequest(url:fileUrl))
  wkWebView.load(URLRequest(url:fileUrl))

both uiWebView and wkWebView can work well. I am confused and can anyone explain that for me: Shouldn't I use URL(string: realPath) for a local resource? But why UIWebView can use it ?

Answer

Code Different picture Code Different · Dec 14, 2016

A couple points:

  1. Apple recommends that you use WKWebview for iOS 8 and later. I would avoid writing new code with UIWebView.

In apps that run in iOS 8 and later, use the WKWebView class instead of using UIWebView. Additionally, consider setting the WKPreferences property javaScriptEnabled to false if you render files that are not supposed to run JavaScript.

  1. Apple has been trying to move away from path and instead wants to use URI even for local files. They recommend that you NOT use /path/to/file.png and use file:///path/to/file.png instead.

As to why one URL works and the other does not, let's make a minimal example:

let realPath = "/path/to/file.png"
let url = URL(string: realPath)               // /path/to/file.png
let fileUrl = URL(fileURLWithPath: realPath)  // file:///path/to/file.png
  • url does not provide the scheme (a.k.a protocol). It should only be used in conjunction with another URL to give the absolute address of the resource you are trying to reach. UIWebView supports it for backwards-compatibility reasons but Apple decided to start clean with WKWebView.
  • fileURL has a scheme (file://) that tells the resource is located on the local file system. Other common schemes are http, https, ftp, etc. It's a complete address to a resource so both views know how to resolve it.