Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
307 views
in Technique[技术] by (71.8m points)

ios - Images from document directory is not visible in Webview.(It is working fine for simulator, causing issue for device only)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...