To show HTML text on UILabel we need to convert the text to NSAttributedString. To achieve this we can use following code:
if let htmlData = htmlString.data(using: String.Encoding.utf16, allowLossyConversion: false) {
if let attributedString = try? NSMutableAttributedString(data: htmlData, options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil) {
label.attributedText = attributedString
}
}
We can also make an extension on String class like so:
extension String {
func attributedString() -> NSAttributedString? {
if let htmlData = self.data(using: String.Encoding.utf16, allowLossyConversion: false) {
if let attributedString = try? NSMutableAttributedString(data: htmlData, options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil) {
return attributedString
}
}
return nil
}
}
In Objective-C following method can be used:
- (NSAttributedString *)attributedStringFromHtml:(NSString *)htmlString {
NSData *data = [htmlString dataUsingEncoding:NSUTF16StringEncoding allowLossyConversion:false];
NSError *err;
NSAttributedString *attr = [[NSAttributedString alloc] initWithData:data options:@{NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType} documentAttributes:nil error:&err];
if (err) {
NSLog(@"Error while converting: %@",err.localizedDescription);
}
return attr;
}
0 Comment(s)