json - How do I decode HTML entities in swift? -
i pulling json file site , 1 of strings received is:
the weeknd ‘king of fall’ [video premiere] | @theweeknd | #sophi
how can convert things ‘
correct characters?
i've made xcode playground demonstrate it:
import uikit var error: nserror? let blogurl: nsurl = nsurl.urlwithstring("http://sophisticatedignorance.net/api/get_recent_summary/") let jsondata = nsdata(contentsofurl: blogurl) let datadictionary = nsjsonserialization.jsonobjectwithdata(jsondata, options: nil, error: &error) nsdictionary var = datadictionary["posts"] nsarray println(a[0]["title"])
there's no straightforward way that, can use nsattributedstring
magic make process painless possible (be warned method strip html tags well):
let encodedstring = "the weeknd <em>‘king of fall’</em>" // encodedstring should = a[0]["title"] in case guard let data = htmlencodedstring.data(using: .utf8) else { return nil } let options: [string: any] = [ nsdocumenttypedocumentattribute: nshtmltextdocumenttype, nscharacterencodingdocumentattribute: string.encoding.utf8.rawvalue ] guard let attributedstring = try? nsattributedstring(data: data, options: options, documentattributes: nil) else { return nil } let decodedstring = attributedstring.string // weeknd ‘king of fall’
remember initialize nsattributedstring main thread only. uses webkit magic underneath, requirement.
you can create own string
extension increase reusability:
extension string { init?(htmlencodedstring: string) { guard let data = htmlencodedstring.data(using: .utf8) else { return nil } let options: [string: any] = [ nsdocumenttypedocumentattribute: nshtmltextdocumenttype, nscharacterencodingdocumentattribute: string.encoding.utf8.rawvalue ] guard let attributedstring = try? nsattributedstring(data: data, options: options, documentattributes: nil) else { return nil } self.init(attributedstring.string) } } let encodedstring = "the weeknd <em>‘king of fall’</em>" let decodedstring = string(htmlencodedstring: encodedstring)
Comments
Post a Comment