【问题标题】:HTML tags in String, convert to normal String字符串中的 HTML 标签,转换为普通字符串
【发布时间】:2020-08-17 21:31:36
【问题描述】:

Html 标签来自 api 响应的字符串,需要显示格式化字符串而不是标签。以下是我尝试过的代码:

html 字符串:

"<span class="st"><em>Bread<\/em> is a staple food, usually by baking. Throughout ... <em>Sourdough<\/em> is a type of <em>bread<\/em> produced by dough using naturally occurring yeasts and lactobacilli. ... List of <em>toast<\/em> dishes<\/span>",
  

代码尝试:

let data = Data(vm.description!.utf8)
if let attributedString = try? NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.html], documentAttributes: nil) {
        infoDescription.attributedText = attributedString
}

尝试了其他方法:

extension String {
    var htmlToAttributedString: NSAttributedString? {
        guard let data = data(using: .utf8) else { return nil }
        do {
            return try NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding:String.Encoding.utf8.rawValue], documentAttributes: nil)
        } catch {
            return nil
        }
    }
    var htmlToString: String {
        return htmlToAttributedString?.string ?? ""
    }
}

请指导我做错了什么或缺少什么。谢谢

【问题讨论】:

标签: html ios swift nsattributedstring


【解决方案1】:

您需要先解码 HTML 实体,然后才能使用当前的实现来获取样式字符串。

对于 HTML 实体解码,您可以参考: https://stackoverflow.com/a/30141700/3867033

但是我发现你可以使用 NSAttributesString 来达到同样的效果。

let html1 = """
<span class="st"><em>Bread</em> is a staple food, usually by baking. Throughout ... <em>Sourdough</em> is a type of <em>bread</em> produced by dough using naturally occurring yeasts and lactobacilli. ... List of <em>toast</em> dishes</span>
"""

extension String {
  var toAttributedString: NSAttributedString? {
    return try? NSAttributedString(
      data: data(using: .utf8)!,
      options: [
        .documentType: NSAttributedString.DocumentType.html,
      ],
      documentAttributes: nil)
  }
}

let output1 = html1.toAttributedString!.string
let output2 = output1.toAttributedString

这对我来说也有点奇怪,但它确实有效......

【讨论】:

  • 你得到了什么?在发帖之前我确实尝试过。
  • 获得相同的值没有任何改变
  • 你确定吗?请注意,您必须像上面的示例一样调用toAttributedString 2 次。
  • 添加了一张图片来展示我从output2得到了什么
  • 输出 1 错误:表达式类型不明确,没有更多上下文
【解决方案2】:

使用String下面的扩展名从字符串中删除html标签

extension String {
    public var withoutHtml: String {
        guard let data = self.data(using: .utf8) else {
            return self
        }

        let options: [NSAttributedString.DocumentReadingOptionKey: Any] = [
            .documentType: NSAttributedString.DocumentType.html,
            .characterEncoding: String.Encoding.utf8.rawValue
        ]

        guard let attributedString = try? NSAttributedString(data: data, options: options, documentAttributes: nil) else {
            return self
        }

        return attributedString.string
    }
}

用法

let formattedStr = yourString?.withoutHtml

【讨论】:

  • 得到相同的字符串没有任何改变
【解决方案3】:

我使用扫描仪将 html 文本转换为普通文本,效果很好。

这个函数去除<>标签之间的文本。

func stripHTML(fromString rawString: String) -> String {
    let scanner = Scanner.init(string: rawString)
    var convertedString = rawString
    while !scanner.isAtEnd {
        let _ = scanner.scanUpToString("<")
        if let text = scanner.scanUpToString(">") {
            convertedString = convertedString.replacingOccurrences(of: "\(text)>", with: "")
        }
    }
    return convertedString
}

查看here 了解扫描仪工作原理的详细说明。

将其用作下面的代码。享受:)

let normalText = stripHTML(fromString: yourHtmlText))

【讨论】:

  • 只检查 ios 13 的错误。在其他类中添加 ios 13 检查开始给出相同的错误
  • 你好@iPhone7,这个新的扫描器API只能在iOS 13上使用。我相信如果你在这个函数上面加上#available(iOS 13.0, *),这将起作用。
猜你喜欢
  • 2018-05-21
  • 2015-10-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-14
  • 1970-01-01
相关资源
最近更新 更多