I am showing HTML files and images in Webview. Fetching files with document directory path:
It is really a strange behaviour where I am able to see images in simulator while for device it only shows HTML Files.
I believe it is not accepting images for path replacedTextRaw.append(resourcePath), I tried with changing baseURL to document directory path.
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
let documentsDirectory = paths[0]
let resourcePath = "(documentsDirectory.path)/Resources/Archive/"
let htmlPath = "(resourcePath)(htmlPath).html"
if let htmlText = try? String(contentsOfFile: htmlPath, encoding: String.Encoding.utf8) {
textRaw.append("<body>(htmlText)</body>")
}
let imgRegex = try NSRegularExpression(pattern: "<img src="([^\.]+)\.([^"]+)"", options: NSRegularExpression.Options.caseInsensitive)
range = NSMakeRange(0, textRaw.count)
imgRegex.enumerateMatches(in: textRaw, options: NSRegularExpression.MatchingOptions.reportCompletion, range: range, using: { result, _, _ in
if let result = result {
let resource: String? = textRaw.substring(with: result.range(at: 1))
let type: String? = textRaw.substring(with: result.range(at: 2))
replacedTextRaw.append(textRaw.substring(with: NSMakeRange(lastValue, result.range.lowerBound - lastValue))!)
replacedTextRaw.append("<img src="")
replacedTextRaw.append(resourcePath)
replacedTextRaw.append("(resource ?? "")@(screenScale)x.(type ?? "")")
replacedTextRaw.append(""")
lastValue = result.range.upperBound
}
})
replacedTextRaw.append(textRaw.substring(with: NSMakeRange(lastValue, textRaw.count - lastValue))!)
replacedTextRaw = "<html>(replacedTextRaw)</html>"
webView.loadHTMLString(replacedTextRaw, baseURL: Bundle.main.bundleURL)
HTML FILE
<img src="image1 1.png" class="top">
<p>Test data </p>
question from:
https://stackoverflow.com/questions/66050435/images-from-document-directory-is-not-visible-in-webview-it-is-working-fine-for 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…