How do I decode HTML entities in Swift?

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

    Swift 5.1 Version

    import UIKit
    
    extension String {
    
        init(htmlEncodedString: String) {
            self.init()
            guard let encodedData = htmlEncodedString.data(using: .utf8) else {
                self = htmlEncodedString
                return
            }
    
            let attributedOptions: [NSAttributedString.DocumentReadingOptionKey : Any] = [
                .documentType: NSAttributedString.DocumentType.html,
                .characterEncoding: String.Encoding.utf8.rawValue
            ]
    
            do {
                let attributedString = try NSAttributedString(data: encodedData, options: attributedOptions, documentAttributes: nil)
                self = attributedString.string
            } 
            catch {
                print("Error: \(error)")
                self = htmlEncodedString
            }
        }
    }
    

    Also, if you want to extract date, images, metadata, title and description, you can use my pod named:

    .

    Readability kit

提交回复
热议问题