psharanda / Atributika

Convert text with HTML tags, links, hashtags, mentions into NSAttributedString. Make them clickable with UILabel drop-in replacement.
MIT License
1.45k stars 155 forks source link

Can I convert NSAttributed string to HTML String? #10

Closed vinayakparmar92 closed 7 years ago

vinayakparmar92 commented 7 years ago

@psharanda Is there any way I can convert the NSAttributedString that I received using this library back again to HTML String?

psharanda commented 7 years ago

It is not possible to restore original HTML from NSAttributedString, because that string doesn't have the info where from attributes come. Though Atributika uses intermediate structure AttributedText which contains 'detections' array, where you can find all the things were detected (with ranges and type of detection). Using it you can restore original HTML. But guess it will be easier just to save original HTML string.

vinayakparmar92 commented 7 years ago

The HTML string here is basically text from UITextView. In case I save the string then it will be very difficult to keep saved HTML string and UITextView text in sync if the user edits the textview.

vinayakparmar92 commented 7 years ago

I tried using the Native way using NSDocumentTypeDocumentAttribute, but it adds a lot of unnecessary CSS and HTML stuff to the string

psharanda commented 7 years ago

Do you mean that you write HTML in UITextView?

vinayakparmar92 commented 7 years ago

I have to send to server an HTML text. It has got tagging links on some word(a tag). Basically I am implementing user tagging in textview. So when user choose a user from the autocomplete results, I will replace that word with an attributed text which I will get from your library.

e.g: Lets say I my UITextView is named textview, then

print(savedHTMLString) \\ Test user tagging <a href=\“http://app.babychakra.com/user/40770\“>Saravanan</a>
print(textview.text) \\ Test user tagging Saravanan
print(textview.attributedText) \\ Test user tagging Saravanan(highlighted word)
psharanda commented 7 years ago

You should not rely on textview.attributedText for storing state. When you adding user from autocomplete, you need to save range for it explicitly in some external array. Your textview needs to render state, not store it. Also Atributika might be not needed at all for your case.

vinayakparmar92 commented 7 years ago

I totally got the solution that you recommending. Seems like a better idea. Will try doing that. Thanks for the update