I am getting a HTML Response from a webservice Below is the HTML I am getting in response
TopicGud mrng.
\\n
I would rather suggest to extend NSAttributedString with failable convenience init. String is not responsible for making NSAttributedString by it's nature.
extension NSAttributedString {
convenience init?(html: String) {
guard let data = html.data(using: String.Encoding.unicode, allowLossyConversion: false) else {
return nil
}
guard let attributedString = try? NSAttributedString(data: data, options: [NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.html], documentAttributes: nil) else {
return nil
}
self.init(attributedString: attributedString)
}
}
label.attributedText = NSAttributedString(html: "<span> Some <b>bold</b> and <a href='#/userProfile/uname'> Hyperlink </a> and so on </span>")
**// Swift 4 compatible | with setting of colour and font options:**
// add following extension to String:
func htmlAttributed(family: String?, size: CGFloat, color: UIColor) -> NSAttributedString? {
let sizeInPx = (size * 0.75)
do {
let htmlCSSString = "<style>" +
"html *" +
"{" +
"font-size: \(sizeInPx)pt !important;" +
"color: \(color.hexString ?? "#000000") !important;" +
"font-family: \(family ?? "SFUIText-Regular"), SFUIText !important;" +
"}</style> \(self)"
guard let data = htmlCSSString.data(using: String.Encoding.utf8) else {
return nil
}
return try NSAttributedString(data: data,
options: [.documentType: NSAttributedString.DocumentType.html,
.characterEncoding: String.Encoding.utf8.rawValue],
documentAttributes: nil)
} catch {
print("error: ", error)
return nil
}
}
// add following extension to UIColor:
extension UIColor{
var hexString:String? {
if let components = self.cgColor.components {
let r = components[0]
let g = components[1]
let b = components[2]
return String(format: "%02X%02X%02X", (Int)(r * 255), (Int)(g * 255), (Int)(b * 255))
}
return nil
}
}
// Sample Use:
yourLabel.attributedText = locationTitle.htmlAttributed(family: yourLabel.font.fontName,
size: yourLabel.font.pointSize,
color: yourLabel.textColor)
You can do it without any third-party libraries by using attributed text. I believe it does accept HTML fragments, like the one you're getting, but you may want to wrap it in a complete HTML document so that you can specify CSS:
static NSString *html =
@"<html>"
" <head>"
" <style type='text/css'>"
" body { font: 16pt 'Gill Sans'; color: #1a004b; }"
" i { color: #822; }"
" </style>"
" </head>"
" <body>Here is some <i>formatting!</i></body>"
"</html>";
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 300, 200)];
NSError *err = nil;
label.attributedText =
[[NSAttributedString alloc]
initWithData: [html dataUsingEncoding:NSUTF8StringEncoding]
options: @{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType }
documentAttributes: nil
error: &err];
if(err)
NSLog(@"Unable to parse label text: %@", err);
Not concise, but you can mop up the mess by adding a category to UILabel:
@implementation UILabel (Html)
- (void) setHtml: (NSString*) html
{
NSError *err = nil;
self.attributedText =
[[NSAttributedString alloc]
initWithData: [html dataUsingEncoding:NSUTF8StringEncoding]
options: @{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType }
documentAttributes: nil
error: &err];
if(err)
NSLog(@"Unable to parse label text: %@", err);
}
@end
…
[someLabel setHtml:@"Be <b>bold!</b>"];
Here is the swift 2 version:
let htmlStringData = NSString(string: "<strong>Your HTML String here</strong>").dataUsingEncoding(NSUTF8StringEncoding)
guard let html = htmlStringData else { return }
do {
let htmlAttrString = try NSAttributedString(data: html, options: [ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil)
yourLabel.attributedText = htmlAttrString
} catch {
print("An error occured")
}
The above answer in Swift 3:
func htmlAttributedString() -> NSAttributedString? {
guard let data = self.data(using: String.Encoding.utf16, allowLossyConversion: false) else { return nil }
guard let html = try? NSMutableAttributedString(
data: data,
options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
documentAttributes: nil) else { return nil }
return html
}