他们终于解决了这个错误!现在我们可以使用了-[WKWebView loadFileURL:allowingReadAccessToURL:]。显然,这个修复在WWDC 2015视频中值得花几秒钟。介绍Safari View Controller
适用于iOS8~iOS10(Swift 3)
正如Dan Fabulish的回答所说,这是WKWebView的一个错误,显然很快就没有解决,因为他说有一个解决办法:)
解决方法是包含20行代码,包含错误处理和注释,不需要服务器:)func fileURLForBuggyWKWebView8(fileURL: URL) throws -> URL {
// Some safety checks if !fileURL.isFileURL {
throw NSError(
domain: "BuggyWKWebViewDomain",
code: 1001,
userInfo: [NSLocalizedDescriptionKey: NSLocalizedString("URL must be a file URL.", comment:"")])
}
try! fileURL.checkResourceIsReachable()
// Create "/temp/www" directory let fm = FileManager.default
let tmpDirURL = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("www")
try! fm.createDirectory(at: tmpDirURL, withIntermediateDirectories: true, attributes: nil)
// Now copy given file to the temp directory let dstURL = tmpDirURL.appendingPathComponent(fileURL.lastPathComponent)
let _ = try? fm.removeItem(at: dstURL)
try! fm.copyItem(at: fileURL, to: dstURL)
// Files in "/temp/www" load flawlesly :) return dstURL}
并可用作:override func viewDidLoad() {
super.viewDidLoad()
var fileURL = URL(fileURLWithPath: Bundle.main.path(forResource:"file", ofType: "pdf")!)
if #available(iOS 9.0, *) {
// iOS9 and above. One year later things are OK. webView.loadFileURL(fileURL, allowingReadAccessTo: fileURL)
} else {
// iOS8. Things can (sometimes) be workaround-ed // Brave people can do just this // fileURL = try! pathForBuggyWKWebView8(fileURL: fileURL) // webView.load(URLRequest(url: fileURL)) do {
fileURL = try fileURLForBuggyWKWebView8(fileURL: fileURL)
webView.load(URLRequest(url: fileURL))
} catch let error as NSError {
print("Error: " + error.debugDescription)
}
}}