Trying to get text from website and display it in ios? - iphone

Ok I have an exsiting app that I am currently working on an update for. What I am trying to do is when the client updates their website, the app will pull the text from the certain page and display the text in an UITextView? I am trying this approach which works fine except it includes the text of the NavBar? So how do I get the text only and no NavBar?
textView.text = [webView stringByEvaluatingJavaScriptFromString:#"document.documentElement.innerText"];

Well you have two choices from the point i see it at. If you know how long the text in the nav bar is and it is the same character length just use:
NSString *webString = [webView stringByEvaluatingJavaScriptFromString:#"document.documentElement.innerText"];
int length = amount of characters to remove from beginning of string;
webString = [webString substringFromIndex:length];
If you dont know the amount you want to remove you can use the NSScanner which is a bit more complicated but is more flexible.
NSString *webString = [webView stringByEvaluatingJavaScriptFromString:#"document.documentElement.innerText"];
NSScanner *stringScanner = [NSScanner scannerWithString:webString];
NSString *content = [[NSString alloc] init];
while ([stringScanner isAtEnd] == NO) {
[stringScanner scanUpToString:#"Start of the text you want" intoString:null];
[stringScanner scanUpToString:#"End of the text you want" intoString:&content];
}
Hope This Helps :D

Here is the code I am trying to use
NSString *webString = [webView stringByEvaluatingJavaScriptFromString:#"document.documentElement.innerText"];
NSScanner *stringScanner = [NSScanner scannerWithString:webString];
NSString *content = [[NSString alloc] init];
while ([stringScanner isAtEnd] == NO) {
[stringScanner scanUpToString:#"Andalee" intoString:NULL];
[stringScanner scanUpToString:#"Eastern Sun Dance Company Rehearsal Mondays 7:00pm # Cal Arts Academy" intoString:&content];
textView.text = webString; }
Maybe I am approaching it wrong.
Here is the webpage that I am trying to pull from http://andalee.com/andalee/CLASSES.html

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.

UIWebView URL from String without http://

So I check if the string starts with "http://" using the code below, and then I want to add "http://" so that I'm able to open the page in UIWebView.
NSString *firstString = [NSString stringWithFormat:#"%#", URL.text];
NSString *check = [NSString stringWithFormat:#"%#", #"http://"];
if (firstString != check) {
NSString *newString = [NSString stringWithFormat:#"http://%#", URL.text];
newString = [newString substringWithRange:NSMakeRange(7, newString.length - 7)];
URL.text = newString;
}
[WebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:URL.text]]];`
This doesn't work for some reason.
Do you know why?
Somebody posted as I was writing, but either way, here's an answer:
You are making this too difficult. You simply need to use hasPrefix to check for "http". As an example, I use this for my unified search/url bar.
- (IBAction)go:(id)sender {
NSString *inputString = [searchField stringValue];
NSString *outputString = [inputString stringByReplacingOccurrencesOfString:#" " withString:#"+"];
if ([inputString hasPrefix:#"http://"]) {
//Has Prefix
[[webView mainFrame] loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:inputString]]];
}
else
{
//Does not have prefix. Do what you want here. I google it.
NSString *googleString = #"http://google.com/search?q=";
NSString *searchString = [NSString stringWithFormat:#"%#%#", googleString, outputString];
[[webView mainFrame] loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:searchString]]];
}
}
That is for googling instead, you could keep using NSString *newString = [NSString stringWithFormat:#"http://%#", URL.text];
You could add a few more checks as well if you wanted to. Good luck!
firstString != check checks to see if both objects point to the same location in memory. [firstString isEqualToString:check] checks if the two strings are equal. However, what you most likely want to do is if(![firstString hasPrefix:check]). This will check to make sure firstString does not start with check, then you can append check to the start of it. Alternatively, you can do firstString = [firstString stringByReplacingOccurrencesOfString:#"http://" withString:#""];, and then you know it will never start with #"http://"
Try printing what URL.text is before the loadRequest line via NSLog(#"%#",URL.text);
Also the preferred check condition would be if (![firstString isEqualToString:check]) {}

Memory management issues with retrieving particular lines of text from string

I am kind of new to iOS development.
I want to retrieve strings from the text(.rtf) file I have. The file is within my application main bundle. It's content are:
#start word1 First word end word2 Second word end //lots of things to be added later
Code:
path = [[NSBundle mainBundle]pathForResource:#"words" ofType:#"rtf"];
if(path)
{
NSLog(#"path exists");
}
NSError *error = nil;
NSString *file = [[NSString alloc]initWithContentsOfFile:path encoding:NSUTF8StringEncoding error:&error];
if(error)
{
NSLog(#"error");
}
NSString *finalword= [[NSString alloc]init ];
NSString *startfrom = [[NSString alloc] initWithFormat:#"word%i",i+1];
i++;
NSLog(#"%#",startfrom);
NSString *wordoftheday = [[NSString alloc]init ];
NSScanner *scanner = [NSScanner scannerWithString:file];
[scanner scanUpToString:startfrom intoString:nil];
[scanner scanUpToString:#"end" intoString:&wordoftheday];
finalword = [wordoftheday substringFromIndex:[startfrom length]];
NSLog(#"%#",finalword);
Word.text = final word; //change label text
//[final word release];
//[wordoftheday release];
//[file release];
Code is working fine but it leaves me with memory management issues. App crashes if I release the variables in the last commented code.
Also this method is in my viewdidload. I want the label to change text when user click a button. I will have to write the same code again in that method which leaves me with more memory issue.
So looking at these one by one, focusing on the memory issues and not the overall strategy here:
NSString *finalword= [[NSString alloc]init ];
Here you alloc/init a new immutable and empty NSString, and then you end up overwriting the pointer to this later anyway. You should just delete this line. And then you'll need to move the declaration down a few lines to this:
NSString *finalword = [wordoftheday substringFromIndex:[startfrom length]];
Then you have:
NSString *startfrom = [[NSString alloc] initWithFormat:#"word%i",i+1];
This one you need to release later. Or just change it to:
NSString *startfrom = [NSString stringWithFormat:#"word%i",i+1];
Then you have:
NSString *wordoftheday = [[NSString alloc]init ];
Same story as finalword. Except that you do need to define this variable so you can pass it to the scanner later. So change it to:
NSString *wordoftheday = nil;
And lastly, you can release 'file'. That is fine. But you don't want to release 'wordoftheday' or 'finalword' because you don't own those strings. You did not create them yourself.
And one other note:
if(error)
That is not the correct way to check for an error in loading 'file'. You should check the return from the method and then look for an error if and only if the return value was nil. So change that line to:
if(!file)
(OK, that wasn't really a memory issue, but a bug I did notice.)
I think that's all of it at least as far as memory issues. I hope that helps.
make those variables as member variables and release in the dealloc

Using TextField to search from a txt file xcode

I am trying to make a simple iphone program that will allow me to search a keyword when entered into a textfield and then search for it by clicking a rect button. I have searched the site and there is nothing that relates to my current situation. to reiterate, I have a textfield where I would like to enter some text and search for it by clicking a rect button. I have the information i want to search for in a txt file. What is the appropriate way to to go about doing this in xcode for iphone. I appreciate the help, thanks.
If I understand your question correctly, You are trying to find a user defined phrase in a text file.
What you should do is read the file to an NSString, and then search the string for the user defined string.
http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Strings/Articles/SearchingStrings.html
Googled it quickly and found an example (Not written by me!):
NSString *searchFor = #"home";
NSRange range;
for (NSString *string in stringList)
{
range = [word rangeOfString:searchFor];
if (range.location != NSNotFound)
{
NSLog (#"Yay! '%#' found in '%#'.", searchFor, string);
}
}
If I missunderstood you, please update your question so it is better understandable.
Try this:
-(void)searchWord:(NSString *)wordToBeSearched{
NSString* path = [[NSBundle mainBundle] pathForResource:#"wordFile"
ofType:#"txt"];
NSString* content = [NSString stringWithContentsOfFile:path
encoding:NSUTF8StringEncoding
error:NULL];
NSString *delimiter = #"\n";
NSArray *items = [content componentsSeparatedByString:delimiter];
NSString *character = #" ";
BOOL isContain = NO;
for (NSString *wordToBeSearched in items) {
isContain = ([string rangeOfString:wordToBeSearched].location != NSNotFound);
}
return isContain;
}
You can go here for more details

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