How do I decode HTML entities in Swift?

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

    Swift 3.0 version with actual font size conversion

    Normally, if you directly convert HTML content to an attributed string, the font size is increased. You can try to convert an HTML string to an attributed string and back again to see the difference.

    Instead, here is the actual size conversion that makes sure the font size does not change, by applying the 0.75 ratio on all fonts:

    extension String {
        func htmlAttributedString() -> NSAttributedString? {
            guard let data = self.data(using: String.Encoding.utf16, allowLossyConversion: false) else { return nil }
            guard let attriStr = try? NSMutableAttributedString(
                data: data,
                options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
                documentAttributes: nil) else { return nil }
            attriStr.beginEditing()
            attriStr.enumerateAttribute(NSFontAttributeName, in: NSMakeRange(0, attriStr.length), options: .init(rawValue: 0)) {
                (value, range, stop) in
                if let font = value as? UIFont {
                    let resizedFont = font.withSize(font.pointSize * 0.75)
                    attriStr.addAttribute(NSFontAttributeName,
                                             value: resizedFont,
                                             range: range)
                }
            }
            attriStr.endEditing()
            return attriStr
        }
    }
    

提交回复
热议问题