What's the difference between UIWebView and WKWebView when loading local resources
A couple points:
- Apple recommends that you use
WKWebview
for iOS 8 and later. I would avoid writing new code withUIWebView
.
In apps that run in iOS 8 and later, use the
WKWebView
class instead of usingUIWebView
. Additionally, consider setting theWKPreferences
propertyjavaScriptEnabled
tofalse
if you render files that are not supposed to run JavaScript.
- 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 usefile:///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.pnglet 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 withWKWebView
.fileURL
has a scheme (file://
) that tells the resource is located on the local file system. Other common schemes arehttp
,https
,ftp
, etc. It's a complete address to a resource so both views know how to resolve it.
This might be for security reasons, or just how the WKWebView
API was implemented.
WKWebView
has a specific instance method for loading local resources called loadFileURL(_:allowingReadAccessTo:)
. This was introduced in iOS 9.
Note
If you are targeting iOS 8.0 or newer, you should be using WKWebView
instead of UIWebView
. See: https://developer.apple.com/reference/webkit/wkwebview