How to parse HTML page data in iphone app? - iphone

I don't know how to parse HTML page content in iPhone SDK?
I have an iPhone app, in this app I need to show the image and data from the HTML page. I have an HTML page URL, I need to get data from the HTML page URL. Can anyone please guide me to parse HTML content from HTML page and show in iPhone app?
Can you please help me?
EDIT
I have an website in HTML format like this http://www.example.com/mobile/403.html page. I want to develop a native iPhone app for this website. My client wont give the response in XML feed so i need to use this site and parse the HTML contents. This page having many images, live data and tables. Till now i didn't parsed HTML page/content in iPhone SDK. So i need your help to do this? Can you please help me? I hope it is clear comparing with old question. Thanks in advance.

You can add the the image url to the NSMutableArray as code below..
NSMutableArray *array = [[NSMutableArray alloc] init];
NSString *response = [[NSString alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:#"index1" ofType:#"html"] encoding:NSUTF8StringEncoding error:nil];
// NSLog(#"response == %#", response);
NSString *regexStr = #"<a href=\"([^>]*)\">";
//NSString *regexStr = #"<A HREF=\"([^>]*)\">";
NSError *error;
NSInteger i =0;
// NSInteger length =0;
while (i<[response length]) {
NSRegularExpression *testRegex = [NSRegularExpression regularExpressionWithPattern:regexStr options:NSRegularExpressionCaseInsensitive error:&error];
if( testRegex == nil ) NSLog( #"Error making regex: %#", error );
NSTextCheckingResult *result = [testRegex firstMatchInString:response options:0 range:NSMakeRange(i, [response length]-i)];
// NSLog(#"result == %#",result);
NSRange range = [result rangeAtIndex:1];
if (range.location == 0) {
break;
}
NSString * imageUrl = [response substringWithRange:range];
if ([imageUrl hasSuffix:#".jpg"] || [imageUrl hasSuffix:#".gif"] || [imageUrl hasSuffix:#".tiff"] || [imageUrl hasSuffix:#".JPG"] || [imageUrl hasSuffix:#".JPEG"] || [imageUrl hasSuffix:#".png"] || [imageUrl hasSuffix:#".PNG"] || [imageUrl hasSuffix:#".GIF"] || [imageUrl hasSuffix:#".TIFF"]) {
// NSLog(#"%#",imageUrl);
// imageUrl = [imageUrl stringByReplacingOccurrencesOfString:#"/syneye_Portfolio/" withString:#""];
[array addObject:imageUrl];
//[array retain];
}
i= range.location;
//NSLog(#"%i",range.location);
i=i+range.length;
}

You should get the HTML thanks to a networking framework (AFNetworking for instance) and parse it with one of the following options:
custom code
some HTML parsing framework (i don't know any)
loading the HTML in a hidden UIWebView and doing some Javascript inside with stringByEvaluatingJavaScriptFromString:

I still don't understand exactly what you want, but this is what's possible with urls and html pages:
1) The page can be loaded into Safari. Of course a user can do this if the user has the url. But also a native app can launch Safari and supply Safari with the url of the page to load. A native app cannot however launch Safari and give it the actual html page to load, it must the url.
2) A native app can use UIWebView to either a) download and display a html page given a url or: b) If the html exists on the device, then the html page is given to UIWebView then the UIWebView will display it directly.
3) If the intention is to just extract a bit of text or an image or two from the html and then display it,then search for a few postings/tutorials then you can a) load the html page in a hidden UIWebView and use Javascript to access the dom elements or b) if its xhmlt use an xml parser to extract the html tags you are looking for or c) see if there are html parsing frameworks available for html or d) do a hack and string seach for the html tokens in the html directly.
4) Parse the full HTML and display all its contents yourself. Unless this is a very very simple html, without a full set of features and can't handle javascript etc. etc. Do you have a large team and years free in which to write what would effectively be your own browser.
EDIT:
You still keep talking about parsing as if parsing is the same thing as displaying it.
If you just want to display the http page at the url use UIWebView. The UIWebView will parse it AND display it. There's no need for you to parse it yourself. Or launch Safari from you app (but you won't be able to return to your app afterwards).
You say you can't use UIWebView? Why not?
To actually try and parse and display the HTML page yourself would be madness.

Related

Display RSS Feed in iPhone`

I have a list of RSS feeds and I need to display the detail of each feed in iPhone. I got all RSS feeds from the server which I'm displaying in tableview. Now on selecting a row I need to display the discription of RSS Feed which is coming from Server in HTML content like:-
<img border=\"0\" hspace=\"10\" align=\"left\" style=\"margin-top:3px;margin-right:5px;\" src=\"http://timesofindia.indiatimes.com/photo/4881843.cms\" />Cadila Pharmaceutical will seek the govt's nod in two days for initiating clinical trials for a vaccine against swine flu.<img width='1' height='1' src='http://timesofindia.feedsportal.com/c/33039/f/533968/s/1f181b11/mf.gif' border='0'/><div class='mf-viral'><table border='0'><tr><td valign='middle'><img src=\"http://res3.feedsportal.com/images/emailthis2.gif\" border=\"0\" /></td><td valign='middle'><img src=\"http://res3.feedsportal.com/images/bookmark.gif\" border=\"0\" /></td></tr></table></div><br/><br/><img src=\"http://da.feedsportal.com/r/133515347892/u/0/f/533968/c/33039/s/1f181b11/a2.img\" border=\"0\"/><img width=\"1\" height=\"1\" src=\"http://pi.feedsportal.com/r/133515347892/u/0/f/533968/c/33039/s/1f181b11/a2t.img\" border=\"0\"/>
How do I display this HTML Content in our iPhone UI, as this will contain text,hyperlink and images.
Is it proper way to use UIWebview in this case, as UIWebView is heavy weight.
Please read this blog : http://www.raywenderlich.com/2636/how-to-make-a-simple-rss-reader-iphone-app-tutorial,
It is useful for you.
you can do something like below.
first of all
descLbl.text=[self flattenHTML:descLbl.text];//descLbl.text is a text in which you are getting that HTML description...
now in flattenHTML method write like below...
- (NSString *)flattenHTML:(NSString *)html {
NSScanner *thescanner;
NSString *text = nil;
thescanner = [NSScanner scannerWithString:html];
while ([thescanner isAtEnd] == NO) {
[thescanner scanUpToString:#"<" intoString:NULL];
// find end of tag
[thescanner scanUpToString:#">" intoString:&text];
html = [html stringByReplacingOccurrencesOfString:[NSString stringWithFormat:#"\n"] withString:#" "];
// replace the found tag with a space
//(you can filter multi-spaces out later if you wish)
html = [html stringByReplacingOccurrencesOfString:[NSString stringWithFormat:#"%#>", text] withString:#" "];
} // while //
return html;
}
let me know it is working or not..
Happy coding!!!!
If you are planning to show HTML entities as it is, i would suggest to go with UIWebView. You can pass this HTML as a string in method loadHTMLString:
If you want the user to view the content as a web page, then loading the url in UIWebView is the best and easiest way.
Like this:
UIWebView *webView = [[UIWebView alloc] init];
NSURL *pageurl = [NSURL URLWithString:http://www.google.com];
NSURLRequest *request = [NSURLRequest requestWithURL:pageurl];
[webView loadRequest:request];
You can simply use RSSKit library.

iphone: how to get text from web site and show it on application

i have web site that show a text and i update this text every day , i want to show this text on iphone application , how can i get this text from web site from application ?
what should i do ?
thanks
1-> you require to connect with your web server thought HTTP connection.
2-> Make the request to server.
3-> Parse server response that may contain your "Text".
For technical assistance Read below.
http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSURLConnection_Class/Reference/Reference.html
I don't recommend this as the best way to obtain a string from your own web server.
This should point you in the right direction, don't expect it to compile cleanly.
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
/* set headers, etc. on request if needed */
[request setURL:[NSURL URLWithString:#"http://example.com/whatever"]];
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:NULL error:NULL];
NSString *html = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];
NSScanner *scanner = [NSScanner scannerWithString:html];
NSString *token = nil;
[scanner scanUpToString:#"<h1>" intoString:NULL];
[scanner scanUpToString:#"</h1>" intoString:&token];
This will capture text from first h1 tag.
The simplest way is to create a REST API. That might sound tough but it's really easy. On the server side, create a new page which holds only the raw text. Usually it's best to keep it there in JSON/XML format, but a simple text will also work. Now from the iPhone, just contact that address and the response data will contain the text. Parsing an existing page is not something I recommend, because changing that page in the future might result in the app not working anymore.
This is a answer quite late but I think it still might help in your future. You can go into parsing the website and that is the right way to do it but I will show you how to do it a different way, this can also be used to read xml, html, .com, anything and also, .rss so it can read RSS Feeds.
Here :
This can get your first paragraph, if you request I will show you how to get the second paragraph and so on.
//This is your URL
NSURL *URL = [NSURL URLWithString:#"URL HERE"];
//This is the data your pulling (dont change)
NSData *data = [NSData dataWithContentsOfURL:URL];
// Assuming data is in UTF8. (dont change)
NSString *string = [NSString stringWithUTF8String:[data bytes]];
//Your textView your not done.
description.text = string;
//Do this with your textview
NSString *webStringz = description.text;
// Leave this
NSString *mastaString;
mastaString = webStringz;
{
NSString *webString2222 = mastaString;
NSScanner *stringScanner2222 = [NSScanner scannerWithString:webString2222];
NSString *content2222 = [[NSString alloc] init];
//Change <p> to suit your need like <description> or <h1>
[stringScanner2222 scanUpToString:#"<p>" intoString:Nil];
[stringScanner2222 scanUpToString:#"." intoString:&content2222];
NSString *filteredTitle = [content2222 stringByReplacingOccurrencesOfString:#"<p>" withString:#""];
description.text = filteredTitle;
}
Title ? Same deal change the <p> to a <title> in RSS <description> and <title>.
Image ? Same deal change the <p> to what ever your RSS or website uses to get a image to find
But remember for both of them when you change the` you see the link which says stringByReplacingOccurences of you have to change that as well.
out then you have to delete this and make your code like this :
/This is your URL
NSURL *URL = [NSURL URLWithString:#"URL HERE"];
//This is the data your pulling (dont change)
NSData *data = [NSData dataWithContentsOfURL:URL];
// Assuming data is in UTF8. (dont change)
NSString *string = [NSString stringWithUTF8String:[data bytes]];
//Your textView your not done.
description.text = string;
NLog(#"%#", string)
//Do this with your textview
NSString *webStringz = description.text;
// Leave this
NSString *mastaString;
mastaString = webStringz;
Now check your log it shows your whole website html or rss code then you scroll and read it and find your image link and check the code before it and change the String Scanner to your needs which is quite awesome and you have to change the stringByReplacingOccurences of.
Like I said images are a bit tricky when you do it with this method but XML Parsing is a lot easier ONCE you learn it , lol. If you request I will show you how to do it.
Make sure :
If you want me to show you how to do it in XML just comment.
If you want me to show you how to find the second paragraph or image or title or something just comment.
IF YOU NEED ANYTHING JUST COMMENT.
Bye have fun with code I provided, anything wrong JUST COMMENT! !!!!
:D

Local function call from UIWebview

Hi i have an uiwebview, I have prepare the htmlstring format of data to load in webview.
I am using this line to load htmlstring in uiwebview.
[webView loadHTMLString:htmlstring baseURL:[NSURL URLWithString:[NSString stringWithFormat:#"file:/%#//",imagePath]]];
In the html formated string we have an one image button.When i click the image button i want to call one local function in ViewController.m file.
Is it possible ? Please help me .
I am using
<input type=""image"" onclick=""func()"" src=""icon_blog.png"" name=""image"" width=""30"" height=""30"">
<script language=""javascript""> function func(){alert(""hee"");}
But alert not shown in iphone . Any one help me ? Thanks in advance.......
There is no straightforward way to call objective-c code from within page loaded in UIWebView.
The only way is to intercept loading of dummy-pages in UIWebView's delegate (– webView:shouldStartLoadWithRequest:navigationType:). There you can make decisions based on request.URL.
- (BOOL)webView:(UIWebView*)_webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType
{
NSArray *components = [[[request URL] absoluteString] componentsSeparatedByString:#":"];
if ([components count] > 1 && [[components objectAtIndex:0] isEqualToString:#"objc"]) {
if ([[components objectAtIndex:1] isEqualToString:#"someFunctionality"]) {
// Do something
}
return NO;
}
return YES;
}
You can trigger those requests by clicking a link, submitting a FORM, or from JavaScript by setting the window's location like this: window.location = "objc:someFunctionality";.

iphone: can i detect a url type?

I'm currently creating a twitter client for iphone.
Basically, I have three kinds of url types I want to handle:
Standard URL's (e.g. http://www.msn.com)
YouTube URL's
URL's containing links to a stream.
When a user clicks a link.. instead of launching the web view and letting the webview decide whether to load quicktime player & youtube player, I want to be able to handle it within the app.
i.e. how can i code something like:
check link
if link = link.youtube then
load youtube player
if link = link.mp3 stream then
load quicktime player
else
load in webview
Checking youtube is easy, you can just check the domain like
[NSString rangeOfSubstring:#"youtube.com"].location != NSNotFound
The mp3 stream is not so hard, you check for the last extension by getting the last "." and then check it agains the set of video stream format like:
NSArray *possibleExtensions = [url componentsSeparatedByString:#"."];
NSString *extension = [possibleExtensions objectAtIndex:([possibleExtensions count] - 1)];
NSSet *extensionSet = [NSSet setWithObjects: #"mp4", #"mov", #"m4v", #"mpv", #"3gp", nil];
BOOL isStream = [extensionSet containsObject:extension];
If you want to check for normal link, you can use Regular expression:
NSString *regrexUrl = #"\\b((?:[\\w-]+://?|www[.])[^\\s()<>]+(?:\\([\\w\\d]+\\)|(?:[^\\p{Punct}\\s]|/)))";
// Based on http://daringfireball.net/2009/11/liberal_regex_for_matching_urls
NSString *urlString = [YOUR_STRING_HERE stringByMatching:NCPARSER_REGEX_URL capture:1];
if (urlString) {
NSLog(#"It is an url");
}

Change Download File Name in Cocoahttpserver

I'm using cocoahttpserver in an iphone app, but when I try to download it (by clicking a link in the standard demo app), my sqlite file (myDatabase.sqlite) arrives on my Mac Desktop as "Unknown" with no suffix at all. However, when I "Save As..." it provides the name fine. I would prefer it to save the file with the sqlite suffix.
So, it must be the suffix causing the problems????
If this is the problem, I cannot seem to find a way in the classes to download the correct file name BUT then change it when presenting it to the browser (with a suffix like .backup, or .db, or something that works).
Anyone know where in the classes to change the download file name so the browser (Safari) will not call it "unknown"? Thanks.
The proper way to do this is to use the httpHeaders override in your async file class:
- (NSDictionary *)httpHeaders
{
NSString *key = #"Content-Disposition";
NSString *value = [NSString stringWithFormat:#"attachment; filename=\"%#\"", [filePath lastPathComponent]];
return [NSDictionary dictionaryWithObjectsAndKeys:value, key, nil];
}
I found someone else's code (MyAppSales) and in replyToHTTPRequest, I added the Content-Disposition header as below (in one section of the method), and now it works!
if(!isRangeRequest)
{
// Status Code 200 - OK
response = CFHTTPMessageCreateResponse(kCFAllocatorDefault, 200, NULL, kCFHTTPVersion1_1);
NSString *contentLengthStr = [NSString stringWithFormat:#"%qu", contentLength];
CFHTTPMessageSetHeaderFieldValue(response, CFSTR("Content-Length"), (CFStringRef)contentLengthStr);
// ************* added this from MyAppSales
if ([httpResponse isKindOfClass:[HTTPFileResponse class]])
{
NSString *baseName = [(NSString *)[(HTTPFileResponse *)httpResponse filePath] lastPathComponent];
NSString *contentDispoStr = [NSString stringWithFormat:#"Content-Disposition: attachment; filename=\"%#\"", baseName];
CFHTTPMessageSetHeaderFieldValue(response, CFSTR("Content-Disposition"), (CFStringRef)contentDispoStr);
}
}
I had a same problem and solved it by changing client side code. At the client side I add download attribute to tags.
Download
For Example:
Download