我正在尝试从
Bundle
加载 HTML 文件。这是我使用的代码,
let fileUrl = Bundle.main.url(forResource: "index", withExtension: "html")!
webView.loadFileURL(fileUrl, allowingReadAccessTo: fileUrl)
如果它是一个简单的 HTML 文件,我看到
WKWebview
正在加载它们。但是现在我正在尝试加载使用 React Native 创建的 HTML。我没有看到 React 本机 Web 代码有任何问题,因为它在本地加载正常。
查看日志,发现加载*.js文件失败
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta httpEquiv="X-UA-Compatible" content="IE=edge" />
<meta
name="viewport"
content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1.00001, viewport-fit=cover"
/>
<title>Bundle HTML</title>
</head>
<div id="root"></div>
<script src="/bundles/web-4587a25eab359d254810d3f9017eb281.js"></script>
</html>
不确定为什么这个 js 和其他资源无法正常加载。有什么想法吗?
我也为
WKWebView
添加了以下配置。
allowsContentJavaScript
和 allowFileAccessFromFileURLs
一样真实
前路很窄,找不到这条路资源:
<script src="/bundles/web-4587a25eab359d254810d3f9017eb281.js"></script>
您应该手动将此路径替换为应用程序包中的真实路径,因此最终代码可能如下所示
// Get the URL for index.html
guard let fileUrl = Bundle.main.url(forResource: "index", withExtension: "html") else {
fatalError("Failed to load index.html")
}
do {
// Load the HTML file into a string
let htmlString = try String(contentsOf: fileUrl)
// Find and replace the bundle path with a new path inside the main bundle
let bundlePath = Bundle.main.path(forResource: "web-4587a25eab359d254810d3f9017eb281", ofType: "js")!
let newHtmlString = htmlString.replacingOccurrences(of: "/bundles/web-4587a25eab359d254810d3f9017eb281.js", with: bundlePath)
// Load the modified HTML string into the web view
webView.loadHTMLString(newHtmlString, baseURL: fileUrl)
} catch {
print("Error loading HTML file: \(error)")
}