1

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

2 Answers 2

1

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
)
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you, I tried with that (I mean dataFromRange:documentAttributes:error:), but it's not working properly..
What do you mean by 'not working properly'? I tried it myself and it works on my side. Check my initial answer, I added an example.
if pasted content has images and result string not containing img tags containing anchor tags instead.
0

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.

1 Comment

This repository does not convert NSTextAttachment to img tag in html.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.