Cocoa webview iframe (objective c) - html

Good day!
I have an html page with iframe src.... in there. I need to get all HTML content of this frame to NSString.
Could you please advice the best way to do it without redirecting the webview to the src?
Thank you.

You can feed in an html text in an NSAttributedString and extract the string from there.
NSAttributedString * attrString = [[NSAttributedString alloc] initWithData:[htmlString dataUsingEncoding:NSUTF8StringEncoding] options:#{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: #(NSUTF8StringEncoding)} documentAttributes:nil error:nil];
NSString *finalString = [attrString string];

Related

ios: Html parsing iframe tag issue

I am using the default html parser to parse the html text:
NSData *data = [receivedText dataUsingEncoding:NSUTF8StringEncoding];
NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithData:data
options:#{
NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
NSCharacterEncodingDocumentAttribute: #(NSUTF8StringEncoding)}
documentAttributes:nil error:nil];
But when the received html text contains a iframe tag, my app crashes. It gives a bad access code issue.
My html text is
<p dir="ltr">iFrame tag test<iframe src='http://www.test.com/'></iframe></p>
Is there something wrong in the code? App works fine when I replace NSHTMLTextDocumentType with any other type, but I need to use this type only.
I am using UITextView to display it.
Use UIWebView. iframe tags may not work with UITextView

Convert HTML string to plain string Objective-C

I made a UITableView which each cell contains a UILabel. The input is some HTML string (like a website page source), eg from Example Domain:
<body>
<div>
<h1>Example Domain</h1>
<p>This domain is established to be used for illustrative examples in documents. You may use this
domain in examples without prior coordination or asking for permission.</p>
<p>More information...</p>
</div>
</body>
but much larger, over 4000 characters.
I want to convert those HTML strings to plain string, for above example it will be:
Example Domain
This domain is established to be used for illustrative examples in documents. You may use this domain in examples without prior
coordination or asking for permission.
More information...
and then display them in UILabel. Currently I'm using this way:
NSData *htmlData = [htmlString dataUsingEncoding:NSUnicodeStringEncoding];
NSAttributedString *attrString = [[NSAttributedString alloc]
initWithData:HTMLData
options:#{
NSDocumentTypeDocumentAttribute : NSHTMLTextDocumentType
}
documentAttributes:nil
error:nil];
NSString *plainString = attrString.string;
This works fine, but the performance is very bad, which causes flickering when scrolling through the tableView. Is there any more efficient way to do this?
Use Below code:
NSString * htmlString = ...;
NSAttributedString * attrStr = [[NSAttributedString alloc] initWithData:[htmlString dataUsingEncoding:NSUnicodeStringEncoding] options:#{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil];
UILabel * myLabel = [UILabel alloc] init];
myLabel.attributedText = attrStr;

What is the best way to display rich content in an iOS app?

I'm developing an iOS app for a news website, the app gets the content from a URL (JSON).
Every article in the website has a description and in which there might be embedded images. How can I display the embedded HTML images in my UITextView (or maybe UILabel?) ? I have found a class named: RichContentLabel but it isn't compatible with iOS7+. Is there another similar class I could use?
This is a test string with embedded images:
<div> some text here <span> something else</span>
<img src="image source" /> something here too
</div>
If you don't want to use a UIWebView you will need to find a way to get the source URL for the image from your HTML string.
You could do this with NSRegularExpression and then load the imageURL into a UIImageView
EDIT:
I used this website to try my regex.
NSError *error = nil;
NSString *regExPattern = #"img src=\"(.*?)\"";
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regExPattern
options:NSRegularExpressionCaseInsensitive | NSRegularExpressionDotMatchesLineSeparators
error:&error];
NSArray *matches = [regex matchesInString:HTMLString options:0 range:NSMakeRange(0, HTMLString.length)];
for (NSTextCheckingResult *result in [matches reverseObjectEnumerator])
{
NSLog(#"0 %#", [HTMLString substringWithRange:[result rangeAtIndex:0]]);
}
You could use a UIWebView:
UIWebView *myWebView = [UIWebView alloc] init];
[myWebView loadHTMLString:testString baseURL:nil];

Write HTML data to NSPasteboard

I am trying to copy an html data to clipboard on MAC. But when i check the clipboard using (Finder-> Edit Menu -> Show clipboard) it shows nothing. I want the formatted data to be pasted as it is. Below is the code i am using:
NSPasteboard *pb = [NSPasteboard generalPasteboard];
NSAttributedString *htmlString = [[NSAttributedString alloc]initWithString:#"<html><body><b>abcdefgh</b></body></html>"];
NSDictionary *documentAttributes = [NSDictionary dictionaryWithObjectsAndKeys:NSHTMLTextDocumentType, NSDocumentTypeDocumentAttribute, nil];
NSData *htmlData = [htmlString dataFromRange:NSMakeRange(0, htmlString.length) documentAttributes:documentAttributes error:NULL];
[pb declareTypes:[NSArray arrayWithObject:NSHTMLPboardType] owner:nil];
[pb setData:htmlData forType:NSHTMLPboardType];
I will appreciate any help. Thanks!
Update:
To get the html formatted string in clipboard, i tried converting it to Attributed string and then from attributed string to rtf data, it sets the data to clip board perfectly, but when i try to paste the data in html editor ( http://htmleditor.in/ ) it loses some formatting like colour.
NSPasteboard *pb = [NSPasteboard generalPasteboard];
NSString *htmlString = #"<HTML> <BODY> <P><FONT COLOR=\"RED\"><UL><LI>fhhj</LI><LI>juil</LI></UL><B>hello</B> <i>html</i></FONT></P> </BODY></HTML>";
NSDictionary *documentAttributes = [NSDictionary dictionaryWithObjectsAndKeys:NSHTMLTextDocumentType, NSDocumentTypeDocumentAttribute, NSCharacterEncodingDocumentAttribute,[NSNumber numberWithInt:NSUTF8StringEncoding], nil];
NSAttributedString* atr = [[NSAttributedString alloc] initWithData:[htmlString dataUsingEncoding:NSUTF8StringEncoding] options:documentAttributes documentAttributes:nil error:nil];
NSData *rtf = [atr RTFFromRange:NSMakeRange(0, [atr length])
documentAttributes:nil];
[pb declareTypes:[NSArray arrayWithObject:NSRTFPboardType] owner:nil];
[pb setData:rtf forType:NSRTFPboardType];
How to preserve color when pasting to html editor? Text is shown with color on clipboard then why it isn't pasted with color on html editor (http://htmleditor.in/)?
I finally got the issue, the functionality is browser dependent(i don't understand the reason though).
If i paste to the site in safari, it doesn't lose any formatting and works well, but if i paste the same text to same site on chrome, it loses some formatting.
Edit
If you want it copied with the attributes applied, then use
NSAttributedString *attrString = [[NSAttributedString alloc] initWithHTML:#"YOUR HTML CODE" documentAttributes:NULL];
[pb setData:attrString forType: NSPasteboardTypeRTF];

Unable to load html string in UIWebView using loadHTMLString:baseURL in iOS?

I am trying to embed youtube video into my iOS application.For that I have created a UIWebView & trying to load the Youtube video from following here
I have gone through the all the answers for the above problem. Even then its not working.
I have also tried loading very simple HTML
NSString *embedHTML =[NSString stringWithFormat:#"<html><body>Hello World</body></html>"];
[webView loadHTMLString:embedHTML baseURL:nil];
Even then, I am getting compile error Parse Issue Expecte ']'
I have tried cleaning, quitting the XCode & relaunching it again. I donno, I am not able to use that method. How to use the above loadHTMLString method for my UIWebView.
PS : Please do not tag this question as duplicate. I have tried all the solutions in Stackoverflow. Nothing has worked
WebView *webDesc = [[UIWebView alloc]initWithFrame:CGRectMake(12, 50, 276, 228)];
NSString *embedHTML = #"<html><head></head><body><p>1. You agree that you will be the technician servicing this work order?.<br>2. You are comfortable with the scope of work on this work order?.<br>3. You understand that if you go to site and fail to do quality repair for any reason, you will not be paid?.<br>4. You must dress business casual when going on the work order.</p></body></html>";
webDesc.userInteractionEnabled = NO;
webDesc.opaque = NO;
webDesc.backgroundColor = [UIColor clearColor];
[webDesc loadHTMLString: embedHTML baseURL: nil];
- (NSString *)getHTMLContent
{
NSString *cssPath = [[NSBundle mainBundle] pathForResource:#"baseline" ofType:#"css"];
NSData *cssData = [NSData dataWithContentsOfFile:cssPath];
NSString *cssStyle = [[NSString alloc] initWithData:cssData encoding:NSASCIIStringEncoding];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
NSString *subtitle = [NSString stringWithFormat:#"%# | %#", self.article.author, [dateFormatter stringFromDate:self.article.publishedDate]];
NSString *htmlString = [NSString stringWithFormat:#"<html><head><meta name='viewport' content='width=device-width; initial-scale=1.0; maximum-scale=1.0;'></head><style type=\"text/css\">%#</style><body><div id=\"container\"><h1>%#</h1><p class='subtitle'>%#</p>%#</div></body></html>", cssStyle, self.article.title, subtitle, self.article.content];
return htmlString;
}
It is very simple. You just have to add only one line. Try It:
NSString *htmlString = #"<html><head></head><body><p>1. You agree that you will be the technician servicing this work order?.<br>2. You are comfortable with the scope of work on this work order?.<br>3. You understand that if you go to site and fail to do quality repair for any reason, you will not be paid?.<br>4. You must dress business casual when going on the work order.</p></body></html>";
[WebView loadHTMLString: htmlString baseURL: nil];
You probably need to provide more code if you want people to help you. I just used webView in a similar way and it's working fine.
self.webView = [[UIWebView alloc] initWithFrame:myFrame];
self.webView.scalesPageToFit = YES;
[self.webView setBackgroundColor:[UIColor whiteColor]];
//pass the string to the webview
[self.webView loadHTMLString:[[self.itineraryArray objectAtIndex:indexPath.row] valueForKey:#"body"] baseURL:nil];
//add it to the subview
[self.view addSubview:self.webView];
Can you provide more information and code?
it doesnt seems like an issue on webview.Please do add the code where it breaks.Error says you missed a ] somewhere in the code
try to load the url directly into the webview :
UIWebView *webview=[[UIWebView alloc]initWithFrame:CGRectMake(100, 100, 200, 250)];
[webview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:#"http://youtube.com/embed/-0Xa4bHcJu8"]]];