To show text in a WKWebView, escape it first: replace &, <, > and quotes with HTML entities, wrap it in a small page, and pass that page to loadHTMLString(_:baseURL:). Unescaped text loses anything that looks like a tag, and a <script> inside it runs. To turn HTML into a string for a UILabel instead, use NSAttributedString with the HTML document type, on the main thread only.
SWIFT TIPS · UIKIT · WEBKIT
First posted on July 17, 2018 for Swift 4, as "HTML To String Use WKWebview Swift 4". Rewritten on November 18, 2026. The escaping test was run on a Mac in a small macOS program using WebKit's WKWebView, with Swift 6.2.3 (Xcode 26.2) on macOS 26.0.1. The view controller was type-checked against the iOS 26.2 SDK in Swift 5 and Swift 6 modes with iOS 15 as the deployment target, but not run on a device.
In 2018 I had a long paragraph of text and wanted it to look nicer than a UILabel: justified, in Roboto, grey, with no text selection. The post put the text into an HTML page with string interpolation, added a style block and a Google Fonts link, and loaded it into a WKWebView pinned to the screen's edges.
That's a reasonable way to get rich text on screen. The part worth fixing is the interpolation: <body>\(htmlIsi)</body> drops the text into HTML exactly as it is, and HTML reads some characters as markup.
What unescaped text does in a web view
I loaded six sample strings into a WKWebView on a Mac, once as they are and once escaped, then read the page's visible text back with JavaScript (document.body.innerText). The last line converts a short HTML snippet with NSAttributedString, covered further down.
text: Tom & Jerry
unescaped: Tom & Jerry
escaped: Tom & Jerry
text: Price < 5 and size > 3
unescaped: Price < 5 and size > 3
escaped: Price < 5 and size > 3
text: If x<y and y>z, then x<z
unescaped: If xz, then x
escaped: If x<y and y>z, then x<z
text: Write < to show a less-than sign
unescaped: Write < to show a less-than sign
escaped: Write < to show a less-than sign
text: Wrap a word in <b> to make it bold
unescaped: Wrap a word in to make it bold
escaped: Wrap a word in <b> to make it bold
text: Nice post!<script>document.body.dataset.ran = 'yes'</script>
unescaped: Nice post!
escaped: Nice post!<script>document.body.dataset.ran = 'yes'</script>
script ran (unescaped): yes
script ran (escaped): no
script ran (unescaped, allowsContentJavaScript = false): no
NSAttributedString string: "Hello world & friends\n\t\u{2022}\tOne\n\t\u{2022}\tTwo\n"
first conversion took about 533 ms on the main thread
second conversion took about 6 ms
The browser engine is forgiving with a lone & or a < followed by a space, so the first two samples look fine either way. That's what makes the bug easy to miss. The others go wrong:
- In
If x<y and y>z, then x<z, everything from the first<to the>was read as a tag, and the final<zvanished too, leaving "If xz, then x". - Text about HTML, like "write <", showed a different character than the one in the string.
<b>was read as a tag and vanished from the text.- The
<script>ran. That matters as soon as the text comes from an API, a user comment or anywhere you don't control.
Escaped, every sample showed exactly what the string held, and the script stayed plain text. Turning off content JavaScript with allowsContentJavaScript = false also stopped the script in the unescaped case, so I use both: escaping keeps the text correct, and the setting is a second guard.
A screen that shows text through a web view
import UIKit
import WebKit
enum HTMLText {
/// Escapes the five characters that HTML treats as markup.
static func escape(_ text: String) -> String {
var out = ""
for ch in text {
switch ch {
case "&": out += "&"
case "<": out += "<"
case ">": out += ">"
case "\"": out += """
case "'": out += "'"
default: out.append(ch)
}
}
return out
}
/// Plain text to paragraphs: a blank line starts a new paragraph.
static func paragraphs(from text: String) -> String {
text.components(separatedBy: "\n\n")
.map { "<p>" + escape($0).replacingOccurrences(of: "\n", with: "<br>") + "</p>" }
.joined()
}
static func page(body: String) -> String {
"""
<!doctype html>
<html><head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
:root { color-scheme: light dark; }
body { font: -apple-system-body; line-height: 1.5; margin: 16px; }
</style>
</head><body>\(body)</body></html>
"""
}
}
final class ArticleTextViewController: UIViewController {
private let text: String
private let webView: WKWebView = {
let config = WKWebViewConfiguration()
// Second safety layer: scripts inside the content never run.
config.defaultWebpagePreferences.allowsContentJavaScript = false
let web = WKWebView(frame: .zero, configuration: config)
web.translatesAutoresizingMaskIntoConstraints = false
return web
}()
init(text: String) {
self.text = text
super.init(nibName: nil, bundle: nil)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .systemBackground
view.addSubview(webView)
NSLayoutConstraint.activate([
webView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor),
webView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
webView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
webView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
])
let html = HTMLText.page(body: HTMLText.paragraphs(from: text))
webView.loadHTMLString(html, baseURL: nil)
}
}
/// HTML from your own server to an attributed string for a UILabel.
/// Main thread only, and keep it out of cellForRowAt.
@MainActor
func attributedText(fromHTML html: String) -> NSAttributedString? {
try? NSAttributedString(
data: Data(html.utf8),
options: [.documentType: NSAttributedString.DocumentType.html,
.characterEncoding: String.Encoding.utf8.rawValue],
documentAttributes: nil)
}
How it works
- Escape, then add your own tags.
HTMLText.paragraphs(from:)escapes the text first and only then adds<p>and<br>, so the only markup on the page is markup you wrote. - The system font.
font: -apple-system-bodyuses the iPhone's body text style instead of a font downloaded from the web. The WebKit team's post introduces these-apple-systemkeywords as iOS's Dynamic Type text styles for web content, each with its own size and weight. - Dark mode.
color-scheme: light darktells WebKit the page can use dark default colors, so the text doesn't stay grey on white when the phone is in dark mode. The 2018 page set its color to a fixed grey. - No scripts.
allowsContentJavaScriptis an iOS 14 setting onWKWebpagePreferences. Apple's documentation says that with it off, the web view doesn't run inline<script>elements,javascript:URLs or other scripts in the content. - No base URL. With
baseURL: nil, relative links and image paths in the HTML have nothing to resolve against. That's fine for text. If you need local images, pass a folder URL in your app bundle as the base URL.
HTML to a string for a UILabel
If the HTML comes from your own server and you only need bold, italics and lists in a label, NSAttributedString can read it. The last line of the test shows the result: tags became formatting, & became &, and list items got a tab and a bullet.
Apple's documentation has two warnings for this. Don't call it from a background thread with the HTML document type: it tries to synchronize with the main thread, fails and times out. And the importer is meant for text styling, not general web pages. It also has a cost: across five runs on my Mac, the first conversion took between about 0.36 and 1.1 seconds and later ones between 6 and 84 milliseconds. Those numbers are from macOS, not an iPhone, but they're enough to keep this out of cellForRowAt. Convert once, keep the result, and reuse it.
A quick check for your project
- Search for
loadHTMLString(and look at how the string is built. Any\(...)inside the HTML should go through an escape function. - Try your screen with the text
a<b and c>d. If part of it disappears, the text isn't escaped. - Search for
.documentType: NSAttributedString.DocumentType.htmland check that it never runs on a background queue or once per table cell.
What the 2018 version said
The original page had two viewport tags, and the second one set maximum-scale=1.0 and user-scalable=0, which stop people from zooming in on small text. It also loaded Roboto from Google Fonts, so the font depended on a network request. The sample text in the post was a paragraph from Kafka's The Metamorphosis.
Keep reading on JR Devhub
Comments