在开发网络应用程序数周期间,我在我的 (WKWebView) WebView 中使用了一个外部 URL。现在我正转向生产,我想嵌入 webapp 并加载本地网页。
我只是从
let url = URL(string: "http://hidden-url.com/")
self.webView!.load(URLRequest(url: url!))
到
let url = URL(string: Bundle.main.path(forResource: "index_prod", ofType: "html")!)
self.webView!.load(URLRequest(url: url!))
但这会导致我的应用程序崩溃。我确定文件已正确加载,并且 print
之前、中间和之后的行将出现在控制台中。
错误:Thread 1: EXC_BAD_ACCESS (code=1, address=0x10)
您需要从文件中加载字符串内容,使用 contentsOfFile 方法获取字符串并使用 webview 的 loadHTMLString 方法,打印错误或创建一些显示错误的枚举
enum WebError: Swift.Error {
case fileNotFound(name: String)
case parsing(contentsOfFile: String)
}
guard let url = Bundle.main.path(forResource: "index_prod", ofType: "html") else {
throw WebError.fileNotFound(name: file) // throw file not found error
}
do {
let html = try String(contentsOfFile: url)
self.webView.loadHTMLString(html, baseURL: Bundle.main.bundleURL)
} catch {
throw WebError.parsingError(contentsOfFile: file)
}