From 29b594207ce34b7979e117af862dcd3db74fcbc6 Mon Sep 17 00:00:00 2001 From: Shadowfacts Date: Mon, 3 Apr 2023 23:39:22 -0400 Subject: [PATCH] Fix crash when comments present in html --- Tusker/HTMLConverter.swift | 29 ++++++++++++++++------------- 1 file changed, 16 insertions(+), 13 deletions(-) diff --git a/Tusker/HTMLConverter.swift b/Tusker/HTMLConverter.swift index 9cc2a28d..d4911408 100644 --- a/Tusker/HTMLConverter.swift +++ b/Tusker/HTMLConverter.swift @@ -32,17 +32,20 @@ struct HTMLConverter { let doc = try! SwiftSoup.parseBodyFragment(html) let body = doc.body()! - let attributedText = attributedTextForHTMLNode(body) - let mutAttrString = NSMutableAttributedString(attributedString: attributedText) - mutAttrString.trimTrailingCharactersInSet(.whitespacesAndNewlines) - mutAttrString.collapseWhitespace() - - mutAttrString.addAttribute(.paragraphStyle, value: paragraphStyle, range: mutAttrString.fullRange) - - return mutAttrString + if let attributedText = attributedTextForHTMLNode(body) { + let mutAttrString = NSMutableAttributedString(attributedString: attributedText) + mutAttrString.trimTrailingCharactersInSet(.whitespacesAndNewlines) + mutAttrString.collapseWhitespace() + + mutAttrString.addAttribute(.paragraphStyle, value: paragraphStyle, range: mutAttrString.fullRange) + + return mutAttrString + } else { + return NSAttributedString() + } } - private func attributedTextForHTMLNode(_ node: Node, usePreformattedText: Bool = false) -> NSAttributedString { + private func attributedTextForHTMLNode(_ node: Node, usePreformattedText: Bool = false) -> NSAttributedString? { switch node { case let node as TextNode: let text: String @@ -65,7 +68,9 @@ struct HTMLConverter { } } - attributed.append(attributedTextForHTMLNode(child, usePreformattedText: usePreformattedText || node.tagName() == "pre")) + if let childText = attributedTextForHTMLNode(child, usePreformattedText: usePreformattedText || node.tagName() == "pre") { + attributed.append(childText) + } if appendEllipsis { attributed.append(NSAttributedString("…")) @@ -134,10 +139,8 @@ struct HTMLConverter { } return attributed - case is DataNode: - return NSAttributedString() default: - fatalError("Unexpected node type \(type(of: node))") + return nil } }