2

I want to show data coming from server in UICollectionView. the data is coming in html string like given below

  <span> recognized <a 

href='#/userProfile/NZ==/XQ=='> Punit Kumar </a> for Delivers on time</span>

I want it to be shown like this

enter image description here

how can I achieve that? Someone please help me.

Mansuu....
  • 1,206
  • 14
  • 27

5 Answers5

7

Swift 4

Update for this answer

    extension NSAttributedString {
        internal convenience init?(html: String) {
            guard let data = html.data(using: String.Encoding.utf16, allowLossyConversion: false) else {
                // not sure which is more reliable: String.Encoding.utf16 or String.Encoding.unicode
                return nil
            }
            guard let attributedString = try? NSMutableAttributedString(data: data, options: [NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.html], documentAttributes: nil) else {
                return nil
            }
            self.init(attributedString: attributedString)
        }
    }

    label.attributedText = NSAttributedString(html: "<span> recognized <a href='#/userProfile/NZ==/XQ=='> Punit Kumar </a> for Delivers on time</span>")
Paul B
  • 3,989
  • 33
  • 46
2

You need to convert your HTML formatted string into NSAttributedString, then set that attributed string as the text of your label. You can convert your HTML formatted string to NSAttributedString using the below extension

extension NSAttributedString {
    internal convenience init?(html: String) {
        guard let data = html.data(using: String.Encoding.utf16, allowLossyConversion: false) else {
            return nil
        }
        guard let attributedString = try? NSMutableAttributedString(data: data, options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil) else {
            return nil
        }
        self.init(attributedString: attributedString)
    }
}

You can use above extension like this: let attributedString = NSAttributedString(html: ""<html><body> Some html string </body></html>"")

Then you can set the attributed string as the text of your UILabel using myLabel.attributedText = attributedString

Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116
  • I am using this extension, but I want to it to be shown exactly the same way as it is shown in above attachment. and the underlined text(Punit kumar) must be clickable – Mansuu.... Jul 24 '17 at 11:22
  • This copies the full HTML formatting, so it should work. What looks different from the picture when you use this method? Are you sure the link is actually referring to something that is valid in the app as well? – Dávid Pásztor Jul 24 '17 at 13:16
  • yeah, the screen shot attached above is actually the screen shot of my android app. – Mansuu.... Jul 24 '17 at 13:19
  • 1
    I just run above code and it displays just as expected. However, to make the link clickable, you will need to do some further work, see [this question](https://stackoverflow.com/questions/1256887/create-tap-able-links-in-the-nsattributedstring-of-a-uilabel). Probably the easiest solution would be to change your `UILabel` to a `UIButton`, which is clickable by default. You can use `button.setAttributedTitle(attributedString, for: .normal)` to set the HTML formatted string as the button's title. – Dávid Pásztor Jul 24 '17 at 13:48
1

Swift 5

let htmlText = "<html><body> Some html string </body></html>"

guard let data = dicData.desc.data(using: String.Encoding.unicode) else { return }

let attributedText = try! NSAttributedString(data: data, options: [.documentType:NSAttributedString.DocumentType.html], documentAttributes: nil)
adiga
  • 34,372
  • 9
  • 61
  • 83
0

Maybe like this

Swift

let htmlText = "<p>etc</p>"

if let htmlData = htmlText.data(using: String.Encoding.unicode) {
    do {
        let attributedText = try NSAttributedString(data: htmlData, options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil)
    } catch let e as NSError {
        print("Couldn't translate \(htmlText): \(e.localizedDescription) ")
    }
}

Objective-C

 NSString * htmlString = @"<html><body> Some html string </body></html>";
NSAttributedString * attrStr = [[NSAttributedString alloc] initWithData:[htmlString dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil];

UILabel * myLabel = [[UILabel alloc] init];
myLabel.attributedText = attrStr;

WebView

[detailView loadHTMLString:[NSString stringWithFormat:@"<div style='text-align:justify; font-size:13px;font-family:HelveticaNeue;color:#362932;'>%@",[model.dict valueForKey:@"description"]] baseURL:nil];
Allan
  • 2,086
  • 1
  • 18
  • 39
  • Thanx @Allan it worked for me. But now I want to apply css too, is there any way to apply external css to that attributed html string – Mansuu.... Aug 29 '17 at 15:01
  • @Mansuu.... Just write the style on the html element. like this

    this is the red font

    – Allan Aug 30 '17 at 01:06
0

Get html attributed string with font parameter from string

extension String
    {
            func getHTMLFromString(htmlText: String,fonthexColor:String,fontName:String,fontSize:Int)->NSAttributedString?
            {
                  let modifiedFont = String(format:"<span style=\"color:\(fonthexColor);font-family:\(fontName); font-size: \(fontSize)\">%@</span>", htmlText)
        
                  let attrStr = try! NSAttributedString(
                      data: modifiedFont.data(using: .unicode, allowLossyConversion: true)!,
                      options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding:String.Encoding.utf8.rawValue],
                      documentAttributes: nil)
             
                  return attrStr
              }
        }