How do I decode HTML entities in Swift?

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

    Swift 4.1 +

    var htmlDecoded: String {
    
    
        let attributedOptions: [NSAttributedString.DocumentReadingOptionKey : Any] = [
    
            NSAttributedString.DocumentReadingOptionKey.documentType : NSAttributedString.DocumentType.html,
            NSAttributedString.DocumentReadingOptionKey.characterEncoding : String.Encoding.utf8.rawValue
        ]
    
    
        let decoded = try? NSAttributedString(data: Data(utf8), options: attributedOptions
            , documentAttributes: nil).string
    
        return decoded ?? self
    } 
    

提交回复
热议问题