-1

In order to convert html to string, I use this 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 ?? ""
    }
}

But text what i get in API i must convert with NSAttributedString.DocumentType.html and sometime with NSAttributedString.DocumentType.plain

How can i combine these two parameters?

Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
Viktor
  • 11
  • 4
  • 2
    I don't understand what you mean by combining the two parameters? What is your desired output? – trndjc Mar 31 '19 at 20:51
  • If the document is a plain text don't use the extension. You can check the url UTI type (if the url points to a html or a txt file) – Leo Dabus Mar 31 '19 at 21:34
  • Can you post some text samples you expect to receive from your API? – Leo Dabus Mar 31 '19 at 21:37
  • Sometime i get html text and all work fine with html parameter, but sometime i get something like this "Hello world.\n\nHello world: \n~ one \n~ two" and extension delete (\n) spaces – Viktor Apr 01 '19 at 07:26

1 Answers1

0

What those extensions do is (1) to create a Data object out of an HTML string, (2) to convert the Data object into an NSAtrributedString object. In other words, it goes like the following.

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>"
    }
}

In the end, you don't need those extensions.

El Tomato
  • 6,479
  • 6
  • 46
  • 75