问题
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 ?
回答1:
A couple points:
- Apple recommends that you use
WKWebviewfor iOS 8 and later. I would avoid writing new code withUIWebView.
In apps that run in iOS 8 and later, use the
WKWebViewclass instead of usingUIWebView. Additionally, consider setting theWKPreferencespropertyjavaScriptEnabledtofalseif 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.pngand usefile:///path/to/file.pnginstead.
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
urldoes 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.UIWebViewsupports it for backwards-compatibility reasons but Apple decided to start clean withWKWebView.fileURLhas 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.
回答2:
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
来源:https://stackoverflow.com/questions/41134493/whats-the-difference-between-uiwebview-and-wkwebview-when-loading-local-resourc