0

I'm using NSURLSession to communicate with a Webservice. However, in the JSON from Webservice I'm getting strings like this Biblotecas de cat& aacute;logos de Marcas i.e. Biblotecas de catálogos de Marcas. I need to get rid of the text cat& aacute;logos and get the original string. How can i do this. I'm using this code for parsing the JSON.

guard let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String:Any] else{

                self.showalertview(messagestring: parseError)
                return
            }
Arun K
  • 810
  • 2
  • 12
  • 33

1 Answers1

3

The best way is to ask the owner of the webservice to send UTF-8 compliant text.

If this is not possible NSAttributedString can decode HTML entities in a very convenient way, this is a String extension adding the computed property htmlDecoded. As the conversion can fail for several reasons the return value is an optional:

extension String {
    var htmlDecoded : String? {
        guard let encodedString = self.data(using: .utf8) else { return nil }
        let options : [String:Any] = [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
                                                NSCharacterEncodingDocumentAttribute: String.Encoding.utf8.rawValue]
        return  try? NSAttributedString(data: encodedString, options: options, documentAttributes: nil).string
    }
}

And use it:

let string = "Biblotecas de catálogos de Marcas"
print(string.htmlDecoded) // "Biblotecas de catálogos de Marcas"
vadian
  • 274,689
  • 30
  • 353
  • 361