如何将html转换为字符串

如何将html转换为字符串,html,swift,Html,Swift,为了将html转换为字符串,我使用以下方法: 但我在API中得到的文本必须使用nsattributestring.DocumentType.html进行转换,有时还必须使用nsattributestring.DocumentType.plain进行转换 如何组合这两个参数?这些扩展所做的是(1)从HTML字符串中创建数据对象,(2)将数据对象转换为NSATrributed字符串对象。换句话说,它如下所示 import UIKit class ViewController: UIViewCont

为了将html转换为字符串,我使用以下方法:

但我在API中得到的文本必须使用
nsattributestring.DocumentType.html进行转换,有时还必须使用
nsattributestring.DocumentType.plain进行转换


如何组合这两个参数?

这些扩展所做的是(1)从HTML字符串中创建
数据
对象,(2)将
数据
对象转换为
NSATrributed字符串
对象。换句话说,它如下所示

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>"
    }
}
导入UIKit
类ViewController:UIViewController{
//标记:-变量
//标记:-IBOutlet
@IBVAR标签:UILabel!
//标记:-IBAction
重写func viewDidLoad(){
super.viewDidLoad()
设htmlStr=makeHTMLString()
让数据=数据(htmlStr.utf8)
如果让attributedString=try?NSAttributedString(数据:数据,选项:[.documentType:NSAttributedString.documentType.html],documentAttributes:nil){
//打印(attributedString.string)
label.attributedText=attributedString
}
}
func makeHTMLString()->字符串{
返回“\n\n Hello,world!\n\n”
}
}

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

我不明白您将这两个参数组合在一起是什么意思?您想要的输出是什么?如果文档是纯文本,请不要使用扩展名。您可以检查url UTI类型(如果url指向html或txt文件)您可以发布一些您希望从API收到的文本示例吗?有时我会得到html文本,所有这些都可以使用html参数,但有时我会得到类似“Hello world。\n\n Hello world:\n~one\n~two”和扩展名delete(\n)空格
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>"
    }
}