Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML from NSAttributedString

Rather than converting HTML to an attributed string, I need to convert it back to HTML. This can easily be done on Mac as can be seen here: http://www.justria.com/2011/01/18/how-to-convert-nsattributedstring-to-html-markup/

Unfortuately, the method dataFromRange:documentAttributes: is only available on Mac via the NSAttributedString AppKit Additions.

My question is how can you do this on iOS?

like image 335
Joshua Avatar asked Jul 03 '11 17:07

Joshua


People also ask

How do I convert HTML to text in Swiftui?

You can convert HTML entities to their equivalent using an extension like this: import UIKit extension String { var decoded: String { let attr = try? NSAttributedString(data: Data(utf8), options: [ . documentType: NSAttributedString.

What is NSAttributedString?

An NSAttributedString object manages character strings and associated sets of attributes (for example, font and kerning) that apply to individual characters or ranges of characters in the string. An association of characters and their attributes is called an attributed string.

What is Nsmutableattributedstring?

A mutable string with associated attributes (such as visual style, hyperlinks, or accessibility data) for portions of its text.

How do you make an attributed string in Swift?

Creating an Attributed String from MarkdownUse Markdown syntax to initialize an attributed string with text and attributes. Use a Markdown-syntax string to iniitalize an attributed string with standard or custom attributes.


2 Answers

Not the 'easy' way, but what about iterating through the attributes of the string using:

- (void)enumerateAttributesInRange:(NSRange)enumerationRange 
                           options:(NSAttributedStringEnumerationOptions)opts 
                        usingBlock:(void (^)(NSDictionary *attrs, NSRange range, BOOL *stop))block

Have an NSMutableString variable to accumulate the HTML (lets call it 'html'). In the block, you would construct the HTML manually using strings. For instance if the text attributes 'attrs' specify red, bold text:

[html appendFormat:@"<span style='color:red; font-weight: bold;'>%@</span>", [originalStr substringWithRange:range]]


EDIT: Stumbled across this yesterday:

NSAttributedString+HTMLFromRange category from "UliKit" (https://github.com/uliwitness/UliKit/blob/master/NSAttributedString+HTMLFromRange.m)

Looks like it will do what you want.

like image 63
Nik Avatar answered Oct 17 '22 02:10

Nik


Use the below code. it works well.

NSAttributedString *s = ...;
NSDictionary *documentAttributes = @{NSDocumentTypeDocumentAttribute:    NSHTMLTextDocumentType};    
NSData *htmlData = [s dataFromRange:NSMakeRange(0, s.length)    documentAttributes:documentAttributes error:NULL];
NSString *htmlString = [[NSString alloc] initWithData:htmlData encoding:NSUTF8StringEncoding];
like image 37
amitshinik Avatar answered Oct 17 '22 02:10

amitshinik