如何将HTML转换为字符串

时间:2019-03-31 20:17:26

标签: html swift

为了将html转换为字符串,我使用以下extension

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 {
        return html2AttributedString?.string ?? ""
    }
}

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

但是要输入我在API中获得的文本,我必须使用NSAttributedString.DocumentType.html进行转换,有时必须使用NSAttributedString.DocumentType.plain进行转换

我如何结合这两个参数?

1 个答案:

答案 0 :(得分:0)

这些扩展的作用是(1)从HTML字符串中创建Data对象,(2)将Data对象转换为NSAtrributedString对象。换句话说,它类似于以下内容。

import UIKit

class ViewController: UIViewController {
    // MARK: - Variables

    // MARK: - IBOutlet
    @IBOutlet weak var label: UILabel!

    // MARK: - IBAction
    override func viewDidLoad() {
        super.viewDidLoad()

        let htmlStr = makeHTMLString()
        let data = Data(htmlStr.utf8)
        if let attributedString = try?NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.html], documentAttributes: nil) {
            //print(attributedString.string)
            label.attributedText = attributedString
        }
    }

    func makeHTMLString() -> String {
        return "<html>\n<head></head>\n<body>\n<h1>Hello, world!</h1>\n</body>\n</html>"
    }
}

最后,您不需要这些扩展名。