无法在iOS Swift中将HTML数据的新段落显示到Textview中

问题描述

我正在使用iOS(Swift)应用程序。我收到一些服务器响应,如下所示。

"description":"This is sample text to show in UI. When doing everyday activities.\u003cbr /\u003eclass is a strong predictor of life,and again sample text here.\u003cbr /\u003eSample text can show here also."

因此,上面的文本有3个段落,我试图在Textview中显示它们,但是用新行而不是新段落以纯文本显示。

    override func viewDidLoad() {
        super.viewDidLoad()

            let description = jsonResponse["description"] as! String
            
            self.textView.attributedText = description.htmlAttributedString()


}
    extension String {
        func htmlAttributedString() -> NSAttributedString? {
            guard let data = self.data(using: String.Encoding.utf16,allowLossyConversion: false) else { return nil }
            guard let html = try? NSMutableAttributedString(
                data: data,options: [NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.html],documentAttributes: nil) else { return nil }
            return html
        }
    }


The issue is it is showing text,But like new line showing instead of new paragraph. How to fix this?

enter image description here

解决方法

我已通过解决此问题,并将服务器转换为json序列化后,特殊字符代码显示为

因此,我已修复如下问题

    let description = jsonResponse["description"] as! String
    let formattedString = description.replacingOccurrences(of: "<br />",with: " \n\n")
    self.textView.text = formattedString

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...