AshokGK
AshokGK

Reputation: 875

how to get html string from NSAttributedString in iOS

I am using UITextview in my app. And I have set allowsEditingTextAttributes property to YES in order to show images and formatted text if user copy pasted from browser into textView and working fine.

I want to retrieve the content back as html from UITextView, is there any way to get it? (I can achieve it using UIWebView but I need to use UITextView only)

Thanks

Upvotes: 1

Views: 1367

Answers (2)

Bensge
Bensge

Reputation: 143

As far as I know, there is no API provided by Apple to do what you want. You need to get the attributed text as an NSAttributedString from the UITextView and convert it to HTML. There are open-source projects for this however, for example DTCoreText. If you're not looking for very advanced features, you might also be able to build this yourself, just by looping through the string's characters and analyzing the style attributes.

EDIT: Actually, there is an API to do this now! You can use NSAttributedString's dataFromRange:documentAttributes:error:, passing NSHTMLTextDocumentType as the requested document type. Cheers!

Example (in Swift, can be done similarly in Objective-C):

//Grab the attributed string, convert it to HTML data
let data = try self.textView.attributedText.dataFromRange(
  NSMakeRange(0, self.textView.attributedText.length),
  documentAttributes: [NSDocumentTypeDocumentAttribute : NSHTMLTextDocumentType]
)

//Convert the UTF-8 data to a string, display it in the text view
self.textView.attributedText = NSAttributedString(
  string: NSString(data: data, encoding: NSUTF8StringEncoding)! as String
)

Upvotes: 1

J. Lopes
J. Lopes

Reputation: 1345

You could take a look at this repository: https://github.com/IdeasOnCanvas/Ashton

To read:

AshtonHTMLReader.h

 - (NSAttributedString *)attributedStringFromHTMLString:(NSString *)htmlString;

And to writer:

AshtonHTMLWriter.h

- (NSString *)HTMLStringFromAttributedString:(NSAttributedString *)input;

See if it can help you.

Upvotes: 0

Related Questions