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

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

Related

Copying HTML using UIPasteBoard and pasting into Gmail

I am trying to find a way to use UIPasteBoard to copy a HTML string into pasteboard, and be able to paste it into different mail clients on iOS.
I tried two accepted answers from StackOverflow: https://stackoverflow.com/a/6566850/1249958 and https://stackoverflow.com/a/21911997/1249958. Those solutions are working on default iOS mail client but they don't make any difference on Gmail.
I know that Gmail accepts HTML input from pasteboard as copying HTML from Safari and pasting that into Gmail app works as expected.
this will put HTML and plain text on the pasteboard and can be pasted into GMail.
UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
NSString *iOSRichContentKey = #"iOS rich content paste pasteboard type";
NSData *iOSRichContent = [iOSRichContentKey dataUsingEncoding:NSUTF8StringEncoding];
NSString *sampleHTML = #"This is <span style='font-weight:bold'>HTML</span>";
NSString *appleWebArchiveKey = #"Apple Web Archive pasteboard type";
NSData *sampleHTMLData = [sampleHTML dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *dict = #{#"WebMainResource": #{#"WebResourceData": sampleHTMLData, #"WebResourceFrameName": #"", #"WebResourceMIMEType": #"text/html", #"WebResourceTextEncodingName": #"UTF-8", #"WebResourceURL": #"about:blank"}};
NSData *appleWebArchive = [NSPropertyListSerialization dataWithPropertyList:dict format:NSPropertyListBinaryFormat_v1_0 options:0 error:nil];
NSString *plainTextKey = #"public.utf8-plain-text";
NSString *plainText = #"this is plain text";
[pasteboard setItems:#[#{iOSRichContentKey : iOSRichContent, appleWebArchiveKey : appleWebArchive, plainTextKey : plainText}]];

ios:how to run html data in ios?

Hi Friends my project is based on parsing datas from JSON, I have done well in parsing datas now my problem is. In one of my module i received some html data from json. Now i need to display in screen by running that html. Is it possible in ios if it possible Please help me how to do it. i have no idea regarding this
Here is the JSON file i received
But its not worked. I need to run that html and have to diaplay in textview pls help me how to do it
Thanks in advance
the content you get is HTML so instead of UITextView use a UIWebView and then use loadHTMLString with it.
///load
//tweet = [[NSDictionary alloc]init]; uneeded
id tweet = [NSJSONSerialization JSONObjectWithData:webData options:kNilOptions error:nil];
id items = tweet[#"aboutUsContent"];
//get html
NSMutableString *html = [NSMutableString string];
for(NSDictionary *item in items) {//it is just one item in your example but ill write the code so it does handle N items
id desc1 = [item valueForKey:#"content"];
[html appendString:desc1];
}
//now set it
[AboutWebView loadHTMLString:str baseURL:nil];
you can take your data into a NSSTRING and load it like this :
[webView loadHTMLString:htmlString baseURL:nil];

iOS NSAttributedString to HTML

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);

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

Encrypted twitter feed

I'm developing an iOS application , that will take a twits from twitter,
I'm using the following API
https://api.twitter.com/1/statuses/user_timeline.json?include_entities=true&include_rts=true&count=2&screen_name=TareqAlSuwaidan
The problem are feed in Arabic Language ,
i.e the text feed appears like this
\u0623\u0646\u0643 \u0648\u0627\u0647\u0645
How can i get the real text (or how to encode this to get real text) ?
This is not encrypted, it is unicode. The codes 0600 - 06ff is Arabic. NSString handles unicode.
Here is an example:
NSString *string = #"\u0623\u0646\u0643 \u0648\u0627\u0647\u0645";
NSLog(#"string: '%#'", string);
NSLog output:
string: 'أنك واهم'
The only question is exactly what problem are you seeing, are you getting the Arabic text? Are you using NSJSONSerialization to deserialize the JSON? If so there should be no problem.
Here is an example with the question URL (don't use synchronous requests in production code):
NSURL *url = [NSURL URLWithString:#"https://api.twitter.com/1/statuses/user_timeline.json?include_entities=true&include_rts=true&count=2&screen_name=TareqAlSuwaidan"];
NSData *data = [NSData dataWithContentsOfURL:url];
NSError *error;
NSArray *jsonObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
NSDictionary *object1 = [jsonObject objectAtIndex:0];
NSString *text = [object1 objectForKey:#"text"];
NSLog(#"text: '%#'", text);
NSLog output:
text: '#Naser_Albdya أيدت الثورة السورية منذ بدايتها وارجع لليوتوب واكتب( سوريا السويدان )
Those are Unicode literals. I think all that's needed is to use NSString's stringWithUTF8String: method on the string you have. That should use NSString's native Unicode handling to convert the literals to the actual characters. Example:
NSString *directFromTwitter = [twitterInterface getTweet];
// directFromTwitter contains "\u0623\u0646\u0643 \u0648\u0627\u0647\u0645"
NSString *encodedString = [NSString stringWithUTF8String:[directFromTwitter UTF8String]];
// encodedString contains "أنك واهم", or something like it
The method call inside the conversion call ([directFromTwitter UTF8String]) is to get access to the raw bytes of the string, that are used by stringWithUTF8String. I'm not exactly sure on what those code points come out to, I just relied on Python to do the conversion.

Resources