为什么 HTML 图像未在 UIWebView 中加载
Why HTML images are not loading in UIWebView
我有一个 HTML 文件导入到我的 Xcode 项目中,里面有一张图片。该图像也在我的项目文件夹中,但是当我尝试在 UIWebView 中加载 HTML 文件时,图像永远不会加载。
这是我的 HTML 文件:
<!DOCTYPE html>
<html>
<body>
<img src="background.png"/>
</body>
</html>
这是我的 Swift 代码,用于加载 HTML 文件:
var htmlFile = NSBundle.mainBundle().pathForResource("Travel", ofType: "html")
var htmlString = try? String(contentsOfFile: htmlFile!, encoding: NSUTF8StringEncoding)
weeb.loadHTMLString(htmlString!, baseURL: nil)
这里出了什么问题?谢谢。
我想你在下面 post 那个人说的
中找到了答案
Using relative paths or file: paths to refer to images does not work
with UIWebView. Instead you have to load the HTML into the view with
the correct baseURL
Using HTML and Local Images Within UIWebView
我遇到了同样的问题。这是我的解决方案
创建一个文件夹,例如 html 并将所有 html 文件与您的图像和其他资源一起放置。然后将该 html 文件夹拖放到您的 xcode 项目中。 xcode 会要求您复制,然后选择选项“创建文件夹引用”,然后完成,查看下面的屏幕截图。
所以您的文件夹结构如下所示。
您的 html 文件将是
<!DOCTYPE html>
<html>
<body>
<img src="back.png"/>
</body>
</html>
要加载此 html 文件,您的 webview 使用以下代码。
let bundlePath = NSBundle.mainBundle().bundlePath
let htmlFile = "\(bundlePath)/html/sample.html"
let fileURL = NSURL(fileURLWithPath: htmlFile)
webview.loadRequest(NSURLRequest(URL: fileURL))
我有一个 HTML 文件导入到我的 Xcode 项目中,里面有一张图片。该图像也在我的项目文件夹中,但是当我尝试在 UIWebView 中加载 HTML 文件时,图像永远不会加载。
这是我的 HTML 文件:
<!DOCTYPE html>
<html>
<body>
<img src="background.png"/>
</body>
</html>
这是我的 Swift 代码,用于加载 HTML 文件:
var htmlFile = NSBundle.mainBundle().pathForResource("Travel", ofType: "html")
var htmlString = try? String(contentsOfFile: htmlFile!, encoding: NSUTF8StringEncoding)
weeb.loadHTMLString(htmlString!, baseURL: nil)
这里出了什么问题?谢谢。
我想你在下面 post 那个人说的
中找到了答案Using relative paths or file: paths to refer to images does not work with UIWebView. Instead you have to load the HTML into the view with the correct baseURL
Using HTML and Local Images Within UIWebView
我遇到了同样的问题。这是我的解决方案
创建一个文件夹,例如 html 并将所有 html 文件与您的图像和其他资源一起放置。然后将该 html 文件夹拖放到您的 xcode 项目中。 xcode 会要求您复制,然后选择选项“创建文件夹引用”,然后完成,查看下面的屏幕截图。
所以您的文件夹结构如下所示。
您的 html 文件将是
<!DOCTYPE html>
<html>
<body>
<img src="back.png"/>
</body>
</html>
要加载此 html 文件,您的 webview 使用以下代码。
let bundlePath = NSBundle.mainBundle().bundlePath
let htmlFile = "\(bundlePath)/html/sample.html"
let fileURL = NSURL(fileURLWithPath: htmlFile)
webview.loadRequest(NSURLRequest(URL: fileURL))