Zander Zander - 4 months ago 11
iOS Question

HTML special keys showing up in post description

I have a UITableView with cells of posts, in the description there are space everywhere, stuff like this everywhere:

  and  


and line breaks. Here is an example post:

Hello,


Text goes here   and more here and even
more  


Notice the massive line break, and weird &; things and the random three or four spaces. So my question is how do I make the description look something like this:

Hello, Text goes here and more here and even
more. And we have room for this now because
we don't have the line breaks.


It would be great if we could make it like the Mail Application description.

Thanks,

Answer

try this solution.

extension String{

  func decodeEnt() -> String{
    let encodedData = self.dataUsingEncoding(NSUTF8StringEncoding)!
    let attributedOptions : [String: AnyObject] = [
        NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
        NSCharacterEncodingDocumentAttribute: NSUTF8StringEncoding
    ]
    var attributedString = NSAttributedString()

    do
    {

     attributedString = try NSAttributedString(data: encodedData, options: attributedOptions, documentAttributes: nil)
    }
    catch
    {
        print("error")
    }

    return attributedString.string
}

//call this to convert string

let encodedString = "The Weeknd ‘King Of The Fall’" // String to convert

let foo = encodedString.decodeEnt()
Comments