问题描述
我正在开发一个应用程序,在该应用程序中我从端点获取数据,然后将其显示给用户。我得到的大多数“字符串”数据都是html格式,因此我需要将其转换为字符串。一切正常,除了删除结尾的换行符。这些是我正在使用的扩展名:
数据扩展名:
extension Data {
var htmlToAttributedString: NSAttributedString? {
do {
return try NSAttributedString(data: self,options: [.documentType: NSAttributedString.DocumentType.html,.characterEncoding: String.Encoding.utf8.rawValue],documentAttributes: nil)
} catch {
print("error:",error)
return nil
}
}
var htmlToString: String {
return htmlToAttributedString?.string ?? ""
}
}
字符串扩展名:
extension String {
var htmlToAttributedString: NSAttributedString? {
return Data(utf8).htmlToAttributedString
}
var htmlToString: String {
return htmlToAttributedString?.string ?? ""
}
}
代码示例:
let descriptionHtml = "\n<p>Rømø beach is still a young beach and created from blown sand so fine that it resembles tiny diamonds. All year round,from morning to evening,there will be activity on the beach,kNown as one of northern Europe’s absolute best and widest.</p>\n"
let descriptionAsstring = descriptionHtml.htmlToString
//Expected result: "Rømø beach is still a young beach and created from blown sand so fine that it resembles tiny diamonds. All year round,kNown as one of northern Europe’s absolute best and widest."
// Actual result: "Rømø beach is still a young beach and created from blown sand so fine that it resembles tiny diamonds. All year round,kNown as one of northern Europe’s absolute best and widest.\n"
//
我可以简单地通过用"\n"
替换""
来解决此问题,但是我似乎并不是一个温和的解决方案,并且由于我使用的是实际的NSAttributedString初始值设定项,这令我感到惊讶,因为它无法正常工作希望它能工作。是否有任何原因使它在末尾保留新的换行符,并且有任何方法可以解决而无需手动替换新的换行符?
解决方法
此文本包含在<p>
标记中。通常,如果呈现了换行符,它将以换行符结尾。这应该是预期的行为。如果您不希望它是“类似段落的”,则它不应放在<p>
标记中。
我删除了<p></p>
,但保留了最后的\n
,它将用尾随空格进行渲染,这是在HTML中渲染换行符的常规方法。同样,这应该是预期的行为。您正在呈现HTML。这样一来,您就可以分块呈现HTML,并以一种明智的方式将生成的字符串粘合在一起。