简体   繁体   中英

Getting attributed html String too from UITextView

I add a attributed text in text view using code given bellow

NSString *string=[NSString stringWithFormat:@"<img src=\"%@\">",sticker.image_url];
NSAttributedString * attrStr = [[NSAttributedString alloc] initWithData:[string dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil];
self.textView.attributedText=attrStr;

the textview has text testing <img src="www.google.com">

above code show image in text view. But now the problem is i want to get string and need to do some more work on it. Thats why when i try to get attributed string from text view using code given below then it only gives text not the html code that i added in the text view.

[self.textview.attributedString string]
return text = testing

Any help please. Acutally i want to show some images using html in text and then need to upload that code on server.

i am unable to understand where that html text goes away, it should stay be some where in the text but i am unable to get that text back Thanks in Advance

You cannot use self.textView.text because what you'll have is just the plain text, at the same time you cannot use self.textView.attributedText since what you'll have is just the NSAttributedString object, that is the representation of what you built using

[[NSAttributedString alloc] initWithData:yourData options:yourOptions documentAttributes:nil error:nil];`

NSAttributedString is not built with html representation in mind, what you used is just a way to easily create a NSAttributedString starting from html, but there is not a complete support between the 2 representations.

You need something slightly more complex that can accomplish this thing, you may want to check this repo https://github.com/IdeasOnCanvas/Ashton

In particular I'm referring to category NSAttributedString+Ashton.h that has this cool method

// Attributed String with CT Attributes
- (NSString *)mn_HTMLRepresentationFromCoreTextAttributes;

I'm not sure about the html tags that the implementation supports, but it is a start anyway.

If your intent is just to save the html that you set for later use, you could subclass NSAttributedString , adding a new property NSString *html that you will set overriding initWithData:options:documentAttributes:error: Obviously it doesn't scale well, but it is a 'dirty' solution in the short run.

将html文本转换为属性字符串后,您将无法找回它,我将文本副本保存在第二个变量中,以备后用。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM