How do I decode HTML entities in Swift?

后端 未结 23 2311
一生所求
一生所求 2020-11-22 01:47

I am pulling a JSON file from a site and one of the strings received is:

The Weeknd ‘King Of The Fall&         


        
23条回答
  •  说谎
    说谎 (楼主)
    2020-11-22 02:48

    extension String{
        func decodeEnt() -> String{
            let encodedData = self.dataUsingEncoding(NSUTF8StringEncoding)!
            let attributedOptions : [String: AnyObject] = [
                NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
                NSCharacterEncodingDocumentAttribute: NSUTF8StringEncoding
            ]
            let attributedString = NSAttributedString(data: encodedData, options: attributedOptions, documentAttributes: nil, error: nil)!
    
            return attributedString.string
        }
    }
    
    let encodedString = "The Weeknd ‘King Of The Fall’"
    
    let foo = encodedString.decodeEnt() /* The Weeknd ‘King Of The Fall’ */
    

提交回复
热议问题