How do I decode HTML entities in Swift?

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

    Elegant Swift 4 Solution

    If you want a string,

    myString = String(htmlString: encodedString)
    

    add this extension to your project:

    extension String {
    
        init(htmlString: String) {
            self.init()
            guard let encodedData = htmlString.data(using: .utf8) else {
                self = htmlString
                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.localizedDescription)")
                self = htmlString
            }
        }
    }
    

    If you want an NSAttributedString with bold, italic, links, etc.,

    textField.attributedText = try? NSAttributedString(htmlString: encodedString)
    

    add this extension to your project:

    extension NSAttributedString {
    
        convenience init(htmlString html: String) throws {
            try self.init(data: Data(html.utf8), options: [
                .documentType: NSAttributedString.DocumentType.html,
                .characterEncoding: String.Encoding.utf8.rawValue
                ], documentAttributes: nil)
        }
    
    }
    

提交回复
热议问题