iOS NSAttributedString to HTML - ios

I have an NSAttributed string (coming from HTML) that I set for a UITextView.
- (void)setHtml:(NSString *)html {
NSData *htmlData = [html dataUsingEncoding:NSUTF8StringEncoding];
// Create the HTML string
NSDictionary *importParams = #{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType};
NSError *error = nil;
self.htmlString = [[NSAttributedString alloc] initWithData:htmlData options:importParams documentAttributes:NULL error:&error];
self.editorView.attributedText = self.htmlString;
}
I then let the user edit what they want, and I would like to then convert it out to HTML again, so I use:
- (NSString *)getHTML {
NSDictionary *exportParams = #{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType};
NSData *htmlData = [self.editorView.attributedText dataFromRange:NSMakeRange(0, self.editorView.attributedText.length) documentAttributes:exportParams error:nil];
return [[NSString alloc] initWithData:htmlData encoding:NSUTF8StringEncoding];
}
It does return HTML, but it isn't how I want it. Everything is given a class attribute, and the CSS it put at the top of the document. Things like images and links are not even included in the returned HTML and probably tons more issues.
Is there a better way to get HTML from an NSAttributedString? Or, is there a way I could parse the NSAttributedString and write my own HTML?

May be you could look at that repository:
https://github.com/IdeasOnCanvas/Ashton
there is 2 interesting class:
AshtonHTMLReader.h
- (NSAttributedString *)attributedStringFromHTMLString:(NSString *)htmlString;
And the writer:
AshtonHTMLWriter.h
- (NSString *)HTMLStringFromAttributedString:(NSAttributedString *)input;
The html generated isn't very nice but if you try to display it in a uiwebview,
it looks pretty good.
Simple idea for image:
encode it with base64 and put it directly in a < img > tag with the right frame.
It's ugly but it works => I've used this process to create and edit some html file few month ago

This is a complex issue, and I will start with a shorter answer. You may ask me questions in the comments, and I will expand on the answer as needed.
We also tried to go the attributed string route, but found it not suited for full HTML editing. Many elements are just not supported, either because the converter is not fully developed, or these elements were deemed outside of scope by Apple. Parsing the attributed string is not good enough, because the attributed string has already lost most of the richness of the HTML by the time you attempt to recreate it.
Instead, we use a webview, load the document normally, and enable contentEditable on the body element. What this does is allow editing of the document in its fullest, limited only by WebKit. At the end, to retrieve the HTML back, we disable contentEditable and take the document.outerHTML to get an entire HTML as it was before, with changes made by the user.
Don't take the decision to implement this method lightly. It is a somewhat complex solution, but certainly possible. A webview is not as nice as a textview, but it can be, given enough massage.
I will expand on this answer as needed.

I also had to convert a NSAtttributedString to HTML in one of my projects. The code for doing this is as follows
//self.attributed String is the attributedString
NSDictionary *documentAttributes = #{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType};
NSData *htmlData = [self.attributedString dataFromRange:NSMakeRange(0, self.attributedString.length) documentAttributes:documentAttributes error:NULL];
NSString *htmlString = [[NSString alloc] initWithData:htmlData encoding:NSUTF8StringEncoding];
NSLog(#"%#", htmlString);

Related

Get unicode chars from webservice and display them in ios app

I need some help:
i get from WebService only a part from the uunicode value, and after this I append the prefix \u to finish the value. The .ttf is good, i tested with some hardcoded values.
NSString *cuvant = [[self.catData objectAtIndex:indexPath.row]objectAtIndex:9]; //Get data
//apend prefix (double \ to escape the \u command)
cuvant = [NSString stringWithFormat:#"\\u%#",cuvant];
// cell.catChar.text = [NSString stringWithUTF8String:"\ue674"]; --->this works very well
cell.catChar.text = [NSString stringWithUTF8String:[cuvant UTF8String]]; //---> this doesn't work
i searched the documentation, and other sites but i didn't found nothing usefull, all the hints are with hardcoded data... i need tot take the codes dinamically
Thanks!
All you need is just to feed this unicoded string as data first. So make a C-String then
NSData *dataFromUnicodedString = [NSData dataWithBytes:yourCUnicodedString length:strlen(yourCUnicodedString)];
and afterwards the resulting string will be
NSString *unicodedString = [[NSString alloc] initWithData:dataFromUnicodedString encoding:NSUTF8StringEncoding];

How can i decode the HTML Code in iOS?

I am using below code to Decode the HTML code:
-(NSString *)decodeString:(NSString *)str
{
// To Remove the HTML code to Nsstring
NSData *stringData = [str dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *options = #{NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType}; NSAttributedString *decodedString;
decodedString = [[NSAttributedString alloc] initWithData:stringData options:options documentAttributes:NULL error:NULL];
return decodedString.string;
}
This code takes a long time to decode the string. So is there is any other way to decode the HTML code?
I don’t want to use the async OR GCD, because I am using this code at the time of stoaring the records in the database.
So please suggest some alternative. Thanks in advance.
If you are storing records in the database then you can use background queue with and Loader or HUD.Because as much data you will decode it will take more time.So in my opinion please make it in background

Formatted text on UITextView

I struck with a small thing i think so, in my app UITextView plays important role. So i like to add formatting feature (Bold, Italics, underline) to it.
Once i tried using,
[NotesTxtView setAllowsEditingTextAttributes:YES];
it works fine but when i save the data to db the formatted texts change to normal. What can i do for that?
Is there any solution for my problem?
Helpers are appreciated,..
You need to save style information also. NSAttributedString's method dataFromRange:documentAttributes:error: will help:
Returns an data object that contains a text stream corresponding to the characters and attributes within the given range.
So you save and restore NSData object from db.
NSDictionary *attrs = #{NSDocumentTypeDocumentAttribute:NSRTFTextDocumentType};
// export data
NSData *data =
[self.textView.attributedText
dataFromRange:NSMakeRange(0, self.textView.text.length)
documentAttributes:attrs
error:nil];
...
// save data to db, fetch later
...
// restore
self.textView.attributedText =
[[NSAttributedString alloc]
initWithData:data
options:nil
documentAttributes:&attrs
error:nil];
Consider using other document types (all available from iOS 7):
NSString *NSPlainTextDocumentType;
NSString *NSRTFTextDocumentType;
NSString *NSRTFDTextDocumentType;
NSString *NSHTMLTextDocumentType;

Get only text and images from <div> in Objective-C

I'm making a news reading application. The best site I found was http://fulltextrssfeed.com/
It takes the text and images from any webpage and gives back clean text. As they don't have an API I need some way to get the data from the <div>.
This is the div ID:
<div id="preview">
How can I leach onto the feed and get only its content (It would be a plus if there are no HTML tags, if there is I can make a work around.)
I'm not sure about your question, but if you're using obj-c, I really recommend Hpple. It's a really good XML/HTML parser.
To use it, you'll need to add ${SDKROOT}/usr/include/libxml2 in "Header Search Path", in your project option and add -lxml2 to "Other Linker Flag".
Then, when you already have the Hpple files, drag it to your code: TFHpple.h, TFHpple.m, TFHppleElement.h, TFHppleElement.m, XPathQuery.h, XPathQuery.m.
In the code (To get your div "preview"), add:
NSData *htmlData = [[NSString stringWithContentsOfURL:[NSURL URLWithString: #"http://www.yoursite.com/index.html"]] dataUsingEncoding:NSUTF8StringEncoding];
TFHpple *xpathParser = [[TFHpple alloc] initWithHTMLData:htmlData];
NSArray *elements = [xpathParser searchWithXPathQuery:#"//div[#id='preview']"]; // Here we use
TFHppleElement *element = [elements objectAtIndex:0];
NSString *string = [element content];
NSLog(#"%#", string);
[xpathParser release];
[htmlData release];
Now we have the "preview div" with Hpple. To get some subclass (as p or a), use it:
NSArray *elements = [xpathParser searchWithXPathQuery:#"//div[#id='preview']/p/text()"];
To undertand more, take a look at XPath Syntax. Also check a tutorial.
Hope it help.
I use this to strip all html very succesfully
NSString + Strip HTML

iOS: How to copy HTML into the cut-paste buffer?

I'm interested in letting my users copy the text they've entered into the cut-and-paste buffer, but I'd like to do that as HTML.
Is such a thing even possible? Or do I need to use a MIME format? (I have no idea.)
Thanks.
The following code will get your HTML out of your app and into Apple's Mail app. The documentation doesn't give you a great deal of help on this, so in part it's a matter of looking at what Apple's apps park on the pasteboard and then reverse engineering that. This solution draws on an earlier stackoverflow post - follow up the links there for more background.
NSLog(#"Place HTML on the pasteboard");
UIPasteboard* pasteboard = [UIPasteboard generalPasteboard];
NSString *htmlType = #"Apple Web Archive pasteboard type";
// example html string
NSString* htmlString = #"<p style=\"color:gray\"> Paragraft<br><em>Less than a word processor, more than plain text</em>";
NSMutableDictionary *resourceDictionary = [NSMutableDictionary dictionary];
[resourceDictionary setObject:[htmlString dataUsingEncoding:NSUTF8StringEncoding] forKey:#"WebResourceData"];
[resourceDictionary setObject:#"" forKey:#"WebResourceFrameName"];
[resourceDictionary setObject:#"text/html" forKey:#"WebResourceMIMEType"];
[resourceDictionary setObject:#"UTF-8" forKey:#"WebResourceTextEncodingName"];
[resourceDictionary setObject:#"about:blank" forKey:#"WebResourceURL"];
NSDictionary *containerDictionary = [NSDictionary dictionaryWithObjectsAndKeys:resourceDictionary, #"WebMainResource", nil];
NSDictionary *htmlItem = [NSDictionary dictionaryWithObjectsAndKeys:containerDictionary,htmlType,nil];
[pasteboard setItems: [NSArray arrayWithObjects: htmlItem, nil]];
// This approach draws on the blog post and comments at:
// http://mcmurrym.wordpress.com/2010/08/13/pasting-simplehtml-into-the-mail-app-ios/
This solution puts both a HTML and a plain text representation into the pasteboard:
#import <MobileCoreServices/MobileCoreServices.h>
NSString *html = #"<h1>Headline</h1>text";
NSData *data = [html dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *dict = #{#"WebMainResource": #{#"WebResourceData": data, #"WebResourceFrameName": #"", #"WebResourceMIMEType": #"text/html", #"WebResourceTextEncodingName": #"UTF-8", #"WebResourceURL": #"about:blank"}};
data = [NSPropertyListSerialization dataWithPropertyList:dict format:NSPropertyListXMLFormat_v1_0 options:0 error:nil];
NSString *archive = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSString *plain = [html stringByReplacingOccurrencesOfRegex:#"<[^>]+>" withString:#""];
[UIPasteboard generalPasteboard].items = #[#{#"Apple Web Archive pasteboard type": archive, (id)kUTTypeUTF8PlainText: plain}];
It uses -stringByReplacingOccurrencesOfRegex: from RegexKitLite to strip the HTML tags.
I absolutely adore this method of creating HTML-based content that you can paste into other HTML-aware apps, like Mail. However, I noticed that the above solution by Matthew Elton only allowed the pasteboard to be pasted onto HTML-aware apps. Trying to paste the exact same content into the Notes app for example, would fail.
I took the tips from this post: https://stackoverflow.com/a/1078471/351810 and can now successfully paste both HTML and plain text versions of the content that I want.
I use w3schools.
I cut and paste my html code over their example code , on any of their many "Try it yourself" tutorials and then use their "run" button.
e.g. https://www.w3schools.com/html/default.asp

Resources