11

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?

2 Answers 2

7

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Yes I was considering that. The most difficult part would be dealing with fonts to see if they are bold, italic or none. I may give it a go now to see how well it works. Thanks!
Great, just noticed the new link (SO doesn't seem to notify when answers are edited) which does everything I want. Thanks, very much! (+1 & ✔)
@Joshua How did this solve your problem? Seems like NSAttributedString+HTMLFromRange is full of OS X-only stuff, no?
@MatthewFrederick I never went on to implement anything using this but the last thing I remember seeing was Cocoanetics DTCoreText. It was only for getting a NSAttributedString from HTML now supports doing it the other way round, i.e getting HTML from the NSAttributedString. You can find DTCoreText on Github here: github.com/Cocoanetics/DTCoreText
For anyone else who needs what Joshua was talking about, its here. Its within the DTCoreText, and for some reason I couldn't find it, but now I have :)
1

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]; 

1 Comment

This works, but it creates a HTML 4 format and not HTML 5.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.