Convert HTML to NSAttributedString in iOS

Related searches

I am using a instance of UIWebView to process some text and color it correctly, it gives the result as HTML but rather than displaying it in the UIWebView I want to display it using Core Text with a NSAttributedString.

I am able to create and draw the NSAttributedString but I am unsure how I can convert and map the HTML into the attributed string.

I understand that under Mac OS X NSAttributedString has a initWithHTML: method but this was a Mac only addition and is not available for iOS.

I also know that there is a similar question to this but it had no answers, I though I would try again and see whether anyone has created a way to do this and if so, if they could share it.

In iOS 7, UIKit added an initWithData:options:documentAttributes:error: method which can initialize an NSAttributedString using HTML, eg:

[[NSAttributedString alloc] initWithData:[htmlString dataUsingEncoding:NSUTF8StringEncoding] 
                                 options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
                                           NSCharacterEncodingDocumentAttribute: @(NSUTF8StringEncoding)} 
                      documentAttributes:nil error:nil];

In Swift:

let htmlData = NSString(string: details).data(using: String.Encoding.unicode.rawValue)
let options = [NSAttributedString.DocumentReadingOptionKey.documentType:
        NSAttributedString.DocumentType.html]
let attributedString = try? NSMutableAttributedString(data: htmlData ?? Data(),
                                                          options: options,
                                                          documentAttributes: nil)

How to convert HTML to an NSAttributedString, By convert HTML using NSAttributedString, I mean converting HTML tags Your ultimate guide to the Google Maps SDK on iOS, using Swift 4� I am able to create and draw the NSAttributedString but I am unsure how I can convert and map the HTML into the attributed string. I understand that under Mac OS X NSAttributedString has a initWithHTML: method but this was a Mac only addition and is not available for iOS.

There is a work-in-progress open source addition to NSAttributedString by Oliver Drobnik at Github. It uses NSScanner for HTML parsing.

How to convert HTML using NSAttributedString, In most cases an iOS app needs to coexist with a web counterpart… At this point we are able to convert HTML into NSAttributedString with a� NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.html], documentAttributes: nil) { yourLabel.attributedText = attributedString } Sponsor Hacking with Swift and reach the world's largest Swift community! Available from iOS 7.0. Similar solutions… How to convert a HTML name string into a UIColor

Creating an NSAttributedString from HTML must be done on the main thread!

Update: It turns out that NSAttributedString HTML rendering depends on WebKit under the hood, and must be run on the main thread or it will occasionally crash the app with a SIGTRAP.

New Relic crash log:

Below is an updated thread-safe Swift 2 String extension:

extension String {
    func attributedStringFromHTML(completionBlock:NSAttributedString? ->()) {
        guard let data = dataUsingEncoding(NSUTF8StringEncoding) else {
            print("Unable to decode data from html string: \(self)")
            return completionBlock(nil)
        }

        let options = [NSDocumentTypeDocumentAttribute : NSHTMLTextDocumentType,
                   NSCharacterEncodingDocumentAttribute: NSNumber(unsignedInteger:NSUTF8StringEncoding)]

        dispatch_async(dispatch_get_main_queue()) {
            if let attributedString = try? NSAttributedString(data: data, options: options, documentAttributes: nil) {
                completionBlock(attributedString)
            } else {
                print("Unable to create attributed string from html string: \(self)")
                completionBlock(nil)
            }
        }
    }
}

Usage:

let html = "<center>Here is some <b>HTML</b></center>"
html.attributedStringFromHTML { attString in
    self.bodyLabel.attributedText = attString
}

Output:

A Swift extension for String and HTML, HTML to NSAttributedString conversion Code :- //HTML String NSString * htmlString=[[NSString alloc]initWithFormat:@"<!DOCTYPE html><html><body>< h1>My� Convert HTML to NSAttributedString in iOS (9) . I am using a instance of UIWebView to process some text and color it correctly, it gives the result as HTML but rather than displaying it in the UIWebView I want to display it using Core Text with a NSAttributedString.

Swift initializer extension on NSAttributedString

My inclination was to add this as an extension to NSAttributedString rather than String. I tried it as a static extension and an initializer. I prefer the initializer which is what I've included below.

Swift 4

internal convenience init?(html: String) {
    guard let data = html.data(using: String.Encoding.utf16, allowLossyConversion: false) else {
        return nil
    }

    guard let attributedString = try?  NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding: String.Encoding.utf8.rawValue], documentAttributes: nil) else {
        return nil
    }

    self.init(attributedString: attributedString)
}

Swift 3

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: [NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.html], documentAttributes: nil) else {
        return nil
    }

    self.init(attributedString: attributedString)
}
}

Example

let html = "<b>Hello World!</b>"
let attributedString = NSAttributedString(html: html)

iOS, As you all know I am writing swift 3 to swift 4.1 conversion issues & solutions. Today I encountered an issue which cannot convert HTML string to NSAttributedString. If you missed to read my post Swift 3 to 4.1 conversion issues. Issue When I try to convert the HTML string to NSAttributedString, getting below error

This is a String extension written in Swift to return a HTML string as NSAttributedString.

extension String {
    func htmlAttributedString() -> NSAttributedString? {
        guard let data = self.dataUsingEncoding(NSUTF16StringEncoding, allowLossyConversion: false) else { return nil }
        guard let html = try? NSMutableAttributedString(data: data, options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil) else { return nil }
        return html
    }
}

To use,

label.attributedText = "<b>Hello</b> \u{2022} babe".htmlAttributedString()

In the above, I have purposely added a unicode \u2022 to show that it renders unicode correctly.

A trivial: The default encoding that NSAttributedString uses is NSUTF16StringEncoding (not UTF8!).

ios - convert - swift 4 nsattributedstring html font Swift- Change font on an HTML string that has its own Styles (4) I am dinamically getting an HTML string from a Wordpress API and parsing it into an Attributed String to show it in my app.

Convert HTML to NSAttributed string and vice verse; Convert NSAttributedString to UIImage; NSAttributedString to UIImage Conversion; Core Data; Core Graphics; Core Location; Core Motion; Core SpotLight in iOS; CoreImage Filters; Create .ipa File to upload on appstore with Applicationloader; Create a Custom framework in iOS; Create a video from

Many elements are just not supported, either because the converter is not fully developed, or these elements were deemed outside of scope by Apple. Parsing the attributed string is not good enough, because the attributed string has already lost most of the richness of the HTML by the time you attempt to recreate it.

Convert HTML to NSAttributed string and vice verse; Objective C code to convert HTML string to NSAttributedString and Vice Versa; Convert NSAttributedString to UIImage; Core Data; Core Graphics; Core Location; Core Motion; Core SpotLight in iOS; CoreImage Filters; Create .ipa File to upload on appstore with Applicationloader; Create a Custom

Comments
  • The NSAttributedString-Additions-for-HTML library has been renamed and rolled into a framework by the same author. It's now called DTCoreText and includes a bunch of Core Text layout classes. You can find it over here
  • For some reason, the option NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType is causing the encoding to take a really, really long time :(
  • Too bad NSHTMLTextDocumentType is (literally) ~1000x slower than setting attributes with NSRange. (Profiled a short label with one bold tag.)
  • Be aware that if you can't NSHTMLTextDocumentType with this method if you want to use it from a background thread. Even with ios 7, it won't use TextKit for the HTML rendering. Take a look at the DTCoreText library recommended by Ingve.
  • Awesome. Just a thought, you could probably do [NSNumber numberWithInt:NSUTF8StringEncoding] as @(NSUTF8StringEncoding), no?
  • I was doing this, but be careful on iOS 8. It's painfully slow, close to a second for a few hundred characters. (In iOS 7 it was nearly instantaneous.)
  • Requires min deployment of iOS 4.3 :( None-the-less, very impressive.
  • @Lirik Overkill for you maybe but perfect for someone else i.e. your comment isn't in the least bit helpful.
  • Please note that this project requires is open source and covered by a standard 2-clause BSD license. That means you have to mention Cocoanetics as the original author of this code and reproduce the LICENSE text inside your app.
  • Andrew. This is working fine. I wanted to know what all short of events that i have to handle in my UITextView if i will go with this approach. Can it handle Calendar event , Call, Email, Website link etc available in HTML? I hope UITextView is able to handle events compare to UILabel.
  • The above approach is only good for formatting. I would recommend using TTTAttributedLabel if you need event handling.
  • The default encoding that NSAttributedString uses is NSUTF16StringEncoding (not UTF8!). That's why this will not work. At least in my case!
  • This should be the accepted solution. Doing an HTML string conversation on a background thread will eventually crash, and quite frequently while running tests.
  • i want hello world to be like this <p><b><i>hello</i></b> <i>world</i></p>