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 &#8216 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>&#8216;king of fall&#8217;</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>&#8216;king of fall&#8217;</em>" let decodedstring = string(htmlencodedstring: encodedstring) 

Comments

Popular posts from this blog

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -

ubuntu - Selenium Node Not Connecting to Hub, Not Opening Port -