If you have full control over the HTML files you could insert a placeholder where you want to insert your value:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div>
<h3>
@@index@@ 如何查询我购买的订单?
</h3>
<p>您好,请微信关注“中通创客”,点击右下角“我的”,选择“订单查询”查询订单信息。
</p>
</div>
</body>
</html>
Then you can load the HTML content into a String
and replace the placeholder with your value before loading the HTML into the WKWebView
:
if let filepath = Bundle.main.path(forResource: "content", ofType: "html") {
do {
let rawHtmlString = try String(contentsOfFile: filepath)
let htmlString = rawHtmlString.replacingOccurrences(of: "@@index@@", with: "17.")
webView.loadHTMLString(htmlString, baseURL: nil)
} catch {
// contents could not be loaded
}
}
If you cannot insert a placeholder and have to use the HTML files as they are you could insert your value like this:
if let filepath = Bundle.main.path(forResource: "content", ofType: "html") {
do {
let rawHtmlString = try String(contentsOfFile: filepath)
// get the ranges of the h3 tags
if let h3OpeningTagRange = rawHtmlString.range(of: "<h3>"), let h3ClosingTagRange = rawHtmlString.range(of: "</h3>") {
// get the text inbetween the h3 tags
let h3Content = rawHtmlString[h3OpeningTagRange.upperBound..<h3ClosingTagRange.lowerBound]
// build the new html string
let htmlString =
// everything until and including the <h3> tag
rawHtmlString[...h3OpeningTagRange.upperBound]
// the value you want to insert
+ "17. "
// the text inbetween the h3 tags
+ h3Content
// the rest of the hmtl including the </h3> tag
+ rawHtmlString[h3ClosingTagRange.lowerBound...]
webView.loadHTMLString(String(htmlString), baseURL: nil)
}
} catch {
// contents could not be loaded
}
}
This gets the range of the opening <h3>
tag and the range of the closing </h3>
tag and constructs the HTML string using those ranges.
This is not a very robust way of doing this, but it might be an easy solution for your special case.