对于以前的 iOS 8 beta,加载一个本地网络应用程序(在 Bundle 中),它对 UIWebView
和 WKWebView
都工作正常,我什至移植了一个网络游戏使用新的 WKWebView
API。
var url = NSURL(fileURLWithPath:NSBundle.mainBundle().pathForResource("car", ofType:"html"))
webView = WKWebView(frame:view.frame)
webView!.loadRequest(NSURLRequest(URL:url))
view.addSubview(webView)
但在 beta 4 中,我只是得到一个空白的白屏(UIWebView
仍然有效),看起来没有加载或执行任何内容。我在日志中看到一个错误:
无法为 /
创建沙箱扩展
有任何帮助可以指导我走向正确的方向吗?谢谢!
最佳答案
他们终于解决了这个错误!现在我们可以使用-[WKWebView loadFileURL:allowingReadAccessToURL:]
。
显然,修复在 WWDC 2015 video 504 Introducing Safari View Controller 中值得几秒钟
适用于 iOS8 ~ iOS10 (Swift 3)
作为Dan Fabulish's answer声明这是 WKWebView 的一个错误显然不会很快得到解决并且正如他所说有一个解决方法:)
我回答只是因为我想在这里展示解决方法。 https://github.com/shazron/WKWebViewFIleUrlTest 中显示的 IMO 代码充满了大多数人可能不感兴趣的无关细节。
变通方法是 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)
}
}
}
关于ios - WKWebView 在 iOS 8 下不加载本地文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24882834/