I have to save htmlstring in DB which maybe bold, italic or underline. I am using below code to get string that i'll save in DB. When i'm getting this saved string from DB into my IOS 10 it is working fine, but in case of ios 11. My text is not got styled(no BOLD or italic etc) that was previously saved in DB, but same text working on IOS 10.
func htmlString() -> String? {
let documentAttributes = [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType]
do {
let htmlData = try self.data(from: NSMakeRange(0, self.length), documentAttributes:documentAttributes)
if let htmlString = String(data:htmlData, encoding:String.Encoding.utf8) {
return htmlString
}
}
catch {}
return nil
}
}
I use the following extension function to customize HTML html String to NSAttributedString and it works great on iOS 10 and 11 (Swift 3.2)
Include character encoding in your options as well:
[NSCharacterEncodingDocumentAttribute : encoding.rawValue]
Extra bonus - i find useful to style HTML text - You can get creative and customize it a bit more if you wish to change fonts and colors.
extension String {
public func htmlAttributedString(regularFont: UIFont, boldFont: UIFont, color: UIColor) -> NSAttributedString {
let encoding = String.Encoding.utf8
guard let descriptionData = data(using: encoding) else {
return NSAttributedString()
}
let options: [String : Any] = [NSDocumentTypeDocumentAttribute : NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute : encoding.rawValue]
guard let attributedString = try? NSMutableAttributedString(data: descriptionData, options: options, documentAttributes: nil) else {
return NSAttributedString()
}
let fullRange = NSMakeRange(0, attributedString.length)
var regularRanges: [NSRange] = []
var boldRanges: [NSRange] = []
attributedString.beginEditing()
attributedString.enumerateAttribute(NSFontAttributeName, in: fullRange, options: .longestEffectiveRangeNotRequired) { (value, range, stop) in
guard let font = value as? UIFont else {
return
}
if font.fontDescriptor.symbolicTraits.contains(.traitBold) {
boldRanges.append(range)
} else {
regularRanges.append(range)
}
}
for range in regularRanges {
attributedString.addAttribute(NSFontAttributeName, value: regularFont, range: range)
}
for range in boldRanges {
attributedString.addAttribute(NSFontAttributeName, value: boldFont, range: range)
}
attributedString.addAttribute(NSForegroundColorAttributeName, value: color, range: fullRange)
attributedString.endEditing()
return attributedString
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With