在 Swift 中将 HTML 转换为纯文本 [英] Convert HTML to Plain Text in Swift

查看:35
本文介绍了在 Swift 中将 HTML 转换为纯文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个简单的 RSS 阅读器应用程序作为 Xcode 中的初学者项目.我目前已将其设置为解析提要,并放置标题、发布日期、描述和内容并将其显示在 WebView 中.

I'm working on a simple RSS Reader app as a beginner project in Xcode. I currently have it set up that it parses the feed, and places the title, pub date, description and content and displays it in a WebView.

我最近决定在用于选择帖子的 TableView 中显示描述(或内容的截断版本).但是,这样做时:

I recently decided to show the description (or a truncated version of the content) in the TableView used to select a post. However, when doing so:

cell.textLabel?.text = item.title?.uppercaseString
cell.detailTextLabel?.text = item.itemDescription //.itemDescription is a String

它显示了帖子的原始 HTML.

It shows the raw HTML of the post.

我想知道如何将 HTML 转换为纯文本,仅用于 TableView 的详细 UILabel.

I would like to know how to convert the HTML into plain text for just the TableView's detailed UILabel.

谢谢!

推荐答案

您可以添加此扩展来将您的 html 代码转换为常规字符串:

You can add this extension to convert your html code to a regular string:

编辑/更新:

讨论 不应从后台调用 HTML 导入器线程(即,选项字典包含带有html 的值).它将尝试与主线程同步,失败,和超时.从主线程调用它是有效的(但仍然可以如果 HTML 包含对外部资源的引用,则超时应该不惜一切代价避免).HTML 导入机制是指用于实现诸如降价之类的东西(即文本样式,颜色等),不适用于一般的 HTML 导入.

Discussion The HTML importer should not be called from a background thread (that is, the options dictionary includes documentType with a value of html). It will try to synchronize with the main thread, fail, and time out. Calling it from the main thread works (but can still time out if the HTML contains references to external resources, which should be avoided at all costs). The HTML import mechanism is meant for implementing something like markdown (that is, text styles, colors, and so on), not for general HTML import.

Xcode 11.4 • Swift 5.2

extension Data {
    var html2AttributedString: 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 html2String: String { html2AttributedString?.string ?? "" }
}

<小时>

extension StringProtocol {
    var html2AttributedString: NSAttributedString? {
        Data(utf8).html2AttributedString
    }
    var html2String: String {
        html2AttributedString?.string ?? ""
    }
}

<小时>

cell.detailTextLabel?.text = item.itemDescription.html2String

这篇关于在 Swift 中将 HTML 转换为纯文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆