How do I decode HTML entities in Swift?

后端 未结 23 1883
一生所求
一生所求 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:34

    Swift 4

    func decodeHTML(string: String) -> String? {
    
        var decodedString: String?
    
        if let encodedData = string.data(using: .utf8) {
            let attributedOptions: [NSAttributedString.DocumentReadingOptionKey : Any] = [
                .documentType: NSAttributedString.DocumentType.html,
                .characterEncoding: String.Encoding.utf8.rawValue
            ]
    
            do {
                decodedString = try NSAttributedString(data: encodedData, options: attributedOptions, documentAttributes: nil).string
            } catch {
                print("\(error.localizedDescription)")
            }
        }
    
        return decodedString
    }
    

提交回复
热议问题