我需要在WebKitView中显示一些图片。这些图片存储在我的Documents目录中。 WebKitView内容是以(非常)长字符串编程方式构建的。
以下是我的称呼方式:
@IBOutlet weak var descView: UIView!
var webView: WKWebView!
let localFile = NSHomeDirectory() + "/Documents/image.png"
let htmlString = "<img src=\"\(localFile)\" />" // for example
let webConfiguration = WKWebViewConfiguration()
webConfiguration.allowsAirPlayForMediaPlayback = true
webConfiguration.allowsInlineMediaPlayback = true
webConfiguration.allowsAirPlayForMediaPlayback = true
if #available(iOS 10.0, *) {
webConfiguration.dataDetectorTypes = .all
}
webView = WKWebView(frame: CGRect(x:0, y:0, width: descView.frame.width, height: descView.frame.height), configuration: webConfiguration)
webView.allowsLinkPreview = true
webView.navigationDelegate = self
webView.uiDelegate = self
let bundlePath = Bundle.main.bundlePath
let baseURL = NSURL.fileURL(withPath: bundlePath)
webView.loadHTMLString(htmlString, baseURL: baseURL)
descView.addSubview(webView)
但图片不存在。
[编辑]因为我使用了捆绑包中的一些脚本,所以需要baseURL。
htmlString可以是:
let htmlHeader = "<!DOCTYPE html><html>\n" +
"<head><script type=\"text/javascript\" async src=\"MathJax-2.7.2/MathJax.js?config=TeX-MML-AM_CHTML\"></script></head>\n" +
"<body style=\"font-size:16pt; text-align:justify;\">"
let htmlFooter = "</body></html>"
let htmlString = htmlHeader + "<img src=\"\(localFile)\" /> $$a^2 + b^2 = c^2$$" + htmlFooter
这应该显示图片及上面的一些乳胶文字。乳胶还可以,没有照片。
答案 0 :(得分:0)
我想问题是您的localFile
路径和/或baseURL
不正确。
NSHomeDirectory() + "/Documents/image.png"
?你打印了要检查的路径吗?NSURL.fileURL(withPath: Bundle.main.bundlePath)
是否正确baseURL
?您正在从主目录加载图像,但是从应用程序包中加载baseUrl
。这不起作用你试过吗
webView.loadHTMLString(htmlString, baseURL: nil)
或
let htmlString = "<img src=\"image.png\" />"
let baseURL = URL(fileURLWithPath: NSHomeDirectory() + "/Documents")
webView.loadHTMLString(htmlString, baseURL: baseURL)
另外,请考虑使用真正的HTML字符串,而不仅仅是图像标记:
let htmlString = "<!DOCTYPE html>" +
"<html>" +
"<head>" +
"<meta charset=\"UTF-8\">" +
"<style type=\"text/css\">" +
"img{position: absolute; top: 0; bottom: 0; left: 0; right: 0; margin: auto; max-width: 100%; max-height: 100%;}" +
"</style>" +
"</head>" +
"<body>" +
"<img src='\(localFile)'/>" +
"</body>" +
"</html>"
答案 1 :(得分:0)
我找到了一个解决方案,可能不是最好但是有效:
let filePath = NSHomeDirectory() + "/Documents/image.jpg"
if FileManager.default.fileExists(atPath: filePath) {
let img = UIImage(contentsOfFile: filePath)!
let imageData = UIImageJPEGRepresentation(img, 85)
let base64String = imageData!.base64EncodedString(options: .lineLength76Characters)
let htmlString = "<img src=\"data:image/jpep;base64,\(base64String)\" alt=\"image.jpg\" />"
}