Ios 从UIWebView中的HTML文件加载内部资源
在我的Xcode 8.2内置的应用程序中,我有一个带有web视图的控制器,其中web视图加载一个内部HTML文件,如下所示:Ios 从UIWebView中的HTML文件加载内部资源,ios,swift,uiwebview,Ios,Swift,Uiwebview,在我的Xcode 8.2内置的应用程序中,我有一个带有web视图的控制器,其中web视图加载一个内部HTML文件,如下所示: let htmlFile = Bundle.main.path(forResource: "web/place-info", ofType: "html") var htmlString = try? String(contentsOfFile: htmlFile!, encoding: String.Encoding.utf8) self.web
let htmlFile = Bundle.main.path(forResource: "web/place-info", ofType: "html")
var htmlString = try? String(contentsOfFile: htmlFile!, encoding: String.Encoding.utf8)
self.webView.loadHTMLString(htmlString!, baseURL: nil)
然后我想在HTML文件中包含一些额外的JavaScript和CSS,但该文件无法加载任何内容。包含路径似乎错误或被阻塞
<link rel="stylesheet" href="web/font-awesome/css/font-awesome.min.css">
更奇怪的是,此图像永远不会加载到place-info.html BODY标记中:
<img src="ic-user-profile.png" />
<img src="/ic-user-profile.png" />
<img src="img/ic-user-profile.png" />
<img src="/img/ic-user-profile.png" />
<img src="web/img/ic-user-profile.png" />
<img src="/web/img/ic-user-profile.png" />
<img src="Project-Name/web/img/ic-user-profile.png" />
<img src="/Project-Name/web/img/ic-user-profile.png" />
<img src="Project-Name/Project-Name/web/img/ic-user-profile.png" />
<img src="/Project-Name/Project-Name/web/img/ic-user-profile.png" />
我是否缺少Xcode 8.2中的一些特殊设置?请注意,在设置中,我已经设置了
应用程序传输安全设置
为允许任意加载=是
罪魁祸首是您将nil传递为baseURL
,并且只给web视图一个要加载的字符串。它不可能知道从何处加载由相对链接引用的文件的位置
因此,只需将place info.html
所在的文件夹作为基本URL传递:
let baseURL = Bundle.main.url(forResource: "web", withExtension: nil)!
let contentURL = baseURL.appendingPathComponent("place-info.html")
let htmlString = try? String(contentsOf: contentURL, encoding: String.Encoding.utf8)
self.webView.loadHTMLString(htmlString!, baseURL: baseURL)
然后,相关链接如
web
文件夹的位置加载资源。注意,我从样式表href中删除了web/
,假设web
文件夹包含font-awesome/css/font-awesome.min.css
:
web/
|- place-info.html
|- ic-user-profile.png
|- font-awesome/
|- css/
|- font-awesome.min.css
除了雅各布·博伊德的评论之外,还请注意美国
在iOS 8及更高版本中运行的应用程序中,请使用WKWeb查看类而不是使用UIWeb视图
进一步强调的是:
重要从iOS 8.0和OS X 10.10开始,使用WKWebView向应用程序添加web内容。不要使用UIWebView或WebView
您的文件的文件夹结构是什么?如果“web”是
中的文件夹名,则让htmlFile=Bundle.main.path(forResource:“web/place info”,of type:“html”)
将其删除为:--让htmlFile=Bundle.main.path(forResource:“place info”,of type:“html”)
。我也会考虑使用一个WKWebVIEW而不是一个UIWebVIEW,用JavaScript可以提高性能。然后您需要在您的服务器上使用webView.configuration.preferences.setValue(true,forKey:“allowFileAccessFromFileURLs”)