Parsing HTML <Tag> into ios - iphone

i am Parsing HTML Tag into iOS using Hpple. i am able to parse the data where the HTML Tag is
<div id="NewsPageSubTitle">
<p><**span** hi how are you>
Using ios code:
NSString *tutorialsXpathQueryString = #"//div[#id='NewsPageArticle']/p/span ";
NSArray *tutorialsNodes = [tutorialsParser searchWithXPathQuery:tutorialsXpathQueryString];
but in few case i don't have span, imean the string in html is accessed by tag "p" directly like:
<div id="NewsPageSubTitle">
<p>< hi how are you>
Here I am using ios code as:
NSString *tutorialsXpathQueryString = #"//div[#id='NewsPageArticle']/p ";
NSArray *tutorialsNodes = [tutorialsParser searchWithXPathQuery:tutorialsXpathQueryString];
but here i am getting a blank data in response.
can any one let me know how to solve the problem?

Since sometimes the para tag has span and sometimes it does not, I would suggest trying to handle that by looping over the children
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"index" ofType:#"html"];
NSData * data = [NSData dataWithContentsOfFile:filePath];
TFHpple * tutorialsParser = [[TFHpple alloc] initWithHTMLData:data];
NSString *tutorialsXpathQueryString = #"//div[#id='NewsPageSubTitle']";
NSArray *tutorialsNodes = [tutorialsParser searchWithXPathQuery:tutorialsXpathQueryString];
for (TFHppleElement * element in tutorialsNodes) {
NSLog(#"%#", element);
NSLog(#"%#", [element tagName]);
NSLog(#"%#", [element attributes]);
NSLog(#"%#", [element children]);
for (TFHppleElement *childElement in [element children]) {
NSLog(#"%#", childElement);
}
}

Check with this: https://github.com/mwaterfall/MWFeedParser
This will provide the HTML Parser for iphone sdk.
More help on:
this blog and here.

NSString *filePath = [[NSBundle mainBundle] pathForResource:#"image" ofType:#"html" inDirectory:#"New Folder 2"];
NSData * data = [NSData dataWithContentsOfFile:filePath];
NSFileHandle *readHandle = [NSFileHandle fileHandleForReadingAtPath:filePath];
NSString *htmlString = [[NSString alloc] initWithData:[readHandle readDataToEndOfFile] encoding:NSUTF8StringEncoding];
TFHpple * Parser = [[TFHpple alloc] initWithHTMLData:data];
NSString *query = #"//p";
NSArray *nodes = [Parser searchWithXPathQuery:query];
for (TFHppleElement *item in nodes)
{
NSLog(#"Title : %#", item.content);
NSLog(#"URL : %#", [item.attributes valueForKey:#"href"]);
}

Related

Reading from text file - Objective C

I am trying to familiarize myself with objective C, and my current goal is to read a list of items in a text file and store them in a NSString array.
Currently this is what I have:
NSString *filepath = [[NSBundle mainBundle] pathForResource:#"myList" ofType:#"txt"];
NSData* data = [NSData dataWithContentsOfFile:filepath];
NSString* string = [[NSString alloc] initWithBytes:[data bytes]
length:[data length]
encoding:NSUTF8StringEncoding];
NSString* delimiter = #"\n";
listArray = [string componentsSeparatedByString:delimiter];
I am not sure if this matters, but myList.txt is in my Supporting Files.
At the moment, I only have one item in my list. However I am unable to store even that 1 item into my listArray.
I am sure it is something silly that I am missing, I am just new to Objective C.
EDIT:
I apologize for not mentioning this earlier. I AM NOT receiving any sort of error. My array is just null.
I'm going to suggest a little simplification which might solve your problem since I can't say what your problem is. From the information I'm not sure if you are getting the proper file contents when reading it in or not.
NSString *filepath = [[NSBundle mainBundle] pathForResource:#"myList" ofType:#"txt"];
NSError *error;
NSString *fileContents = [NSString stringWithContentsOfFile:filepath encoding:NSUTF8StringEncoding error:&error];
if (error)
NSLog(#"Error reading file: %#", error.localizedDescription);
// maybe for debugging...
NSLog(#"contents: %#", fileContents);
NSArray *listArray = [fileContents componentsSeparatedByString:#"\n"];
NSLog(#"items = %d", [listArray count]);
If the content of the file is just like:
[{"Title":"20","Cost":"20","Desc":""},{"Title":"10","Cost":"10.00","Desc":""},{"Title":"5","Cost":"5.00","Desc":""}]
try this
-(id)readFromDocumentDBFolderPath:(NSString *)fileName
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *appFile = [documentsDirectory stringByAppendingPathComponent:fileName];
NSFileManager *fileManager=[NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:appFile])
{
NSError *error= NULL;
NSData* data = [NSData dataWithContentsOfFile:appFile];
id resultData = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
if (error == NULL)
{
return resultData;
}
}
return NULL;
}

Change parts of an NSString

I have a urlString that is: http://www.youtube.com/watch?v=5kdEhVtNFPo
I want to be able to change it into this: http://www.youtube.com/v/5kdEhVtNFPo
How would I go about doing that? I'm not sure if I should use the instance methods substringWithRange: or substringFromIndex:
I tried this which removes the first part and just leaves the video id (it removes http://www.youtube.com/watch?v=) now I just need to add http://www.youtube.com/v/ to the start of the string.
NSString *newUrlString = [urlString substringFromIndex:31];
NSString* newUrl = [oldUrl stringByReplacingOccurrencesOfString:#"watch?v=" withString:#"v/"];
Please note that this only works as long as the URL won't contain more instances of the string "watch?v=".
I'll propose a different way that may be more flexible on the inputs you give it:
- (NSString) newURLStringForOldURLString:(NSString *)oldURLString
{
NSString *newURLString = nil;
NSURL *url = [[NSURL alloc] initWithString:oldURLString];
NSString *query = [url query]; /* v=5kdEhVtNFPo */
NSArray *fieldValuePairs = [query componentsSeparatedByString:#"&"];
for (NSString *pair in fieldValuePairs) {
NSArray *components = [pair componentsSeparatedByString:#"="];
NSString *field = [components objectAtIndex:0];
NSString *value = [components objectAtIndex:1];
if ([field isEqualToString:#"v"]) {
newURLString = [NSString stringWithFormat:#"%#://%#:%#/%#/%#", [url scheme], [url domain], [url port], field, value];
break;
}
}
[url release];
return newURLString;
}
To be flexible enough, you could use NSRegularExpression:
NSString *str = #"http://www.youtube.com/watch?v=5kdEhVtNFPo";
NSString *pattern = #"((?:http:\\/\\/){0,1}www\\.youtube\\.com\\/)watch\\?v=([:alnum:]+)";
NSString *template = #"$1v/$2";
NSRegularExpression *regexp = [NSRegularExpression
regularExpressionWithPattern:pattern
options:NSRegularExpressionCaseInsensitive
error:nil];
NSString *newStr = [regexp stringByReplacingMatchesInString:str
options:0 range:NSMakeRange(0, [str length]) withTemplate:template];
NSLog(#"Replaced: %#", newStr);
Another alternative :
NSString *str3 = #"http://www.youtube.com/watch?v=5kdEhVtNFPo";
NSString *outputString;
NSRange range = [str3 rangeOfString:#"watch?v="];
if(range.location != NSNotFound)
{
outputString = [str3 stringByReplacingCharactersInRange:range withString:#"v/"];
NSLog(#"%#",outputString);
}

Cocoa error 256, When using initWithContentsOfURL:

i getting data from my site:
NSString *website = [NSString stringWithFormat:#"http://www.mysite.com/fbconnect.php?email=%#&name=%#&pass=***", nameTrimmmed, [jsonObject objectForKey:#"email"]];
NSLog(#"%#", website);
NSError *error = nil;
NSString *contents = [[NSString alloc] initWithContentsOfURL:[NSURL URLWithString:website] encoding:NSUTF8StringEncoding error:&error];
contents have Cocoa error 256. where i wrong?
The issue is in Hebrew characters, you should html-escape them, also try request with English characters instead, to see if it works
- (void)yourMethod
{
NSString *name = #"שימרגוליס";
name = AFURLEncodedStringFromStringWithEncoding(name, NSUTF8StringEncoding);
NSString *website = [NSString stringWithFormat:#"http://www.ba-cafe.com/fbconnect.php?email=%#&name=%#&pass=SwHyK17!",#"email#mail.com",name];
NSLog(#"%#", website);
NSError *error = nil;
NSString *contents = [[NSString alloc] initWithContentsOfURL:[NSURL URLWithString:website] encoding:NSUTF8StringEncoding error:&error];
}
Where AFURLEncodedStringFromStringWithEncodingis a function from AFNetworking framework
Check the Console log for NSLog(#"%#", website);
You will see something like this:
http://www.mysite.com/fbconnect.php?email=thetrimmedname&name=emailaddress&pass=***
So do this:
NSString *website = [NSString stringWithFormat:#"http://www.mysite.com/fbconnect.php?email=%#&name=%#&pass=***", [jsonObject objectForKey:#"email"], nameTrimmmed ];
instead of this:
NSString *website = [NSString stringWithFormat:#"http://www.mysite.com/fbconnect.php?email=%#&name=%#&pass=***", nameTrimmmed, [jsonObject objectForKey:#"email"]];
This is because of the dot in the email address.
Look right here:
Error while trying to access Google translate with NSURL

how to capture data through web service (php) sql query select with condition from ios iphone sdk

I have the following php file:
<?php
$username="root";
$database="testdb";
mysql_connect(localhost,$username);
$user=$_GET["user"];
$password=$_GET["password"];
$query="SELECT documento FROM person WHERE user='".$user." and password ='".$password."'";
$result=mysql_query($query) or die (mysql_error("error "));
$num=mysql_numrows($result);
mysql_close();
$rows=array();
while($r=mysql_fetch_assoc($result)){
$rows[]=$r;
}
echo json_encode($rows);
?>
to retrieve the information achieved by the following functions but the example did not have the php input conditions and parameters was select * from person here the functions
based in http://www.youtube.com/watch?feature=endscreen&v=IQcLngIDf9k&NR=1
-(void) getData:(NSData *) data{
NSError *error;
json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
}
-(void) start {
NSURL *url = [NSURL URLWithString:kGETUrl];
NSData *data = [NSData dataWithContentsOfURL:url];
[self getData:data];
}
now as the sql statement has input parameters is not as code and tried something like this A Simple PHP/MySQL Web Service for iOS but I can not accommodate what I need.
Pass the parameters in the string. Here is an example
-(void) start {
NSString *user = [[NSString alloc] initWithString:#"exampleuser"];
NSString *password = [[NSString alloc] initWithString:#"examplepassword"];
NSString *urlstr = [[NSString alloc] initWithFormat:#"http://myserver.com/myphpfile.php?user=%#?password=%#", user, password];
NSURL *url = [NSURL URLWithString:urlstr];
NSData *data = [NSData dataWithContentsOfURL:url];
[self getData:data];
}
As it is password and user it normally is better to use POST instead of GET because then it is not part of the URL which is visible. With POST you can hide it if you have a https line. But I think this is not your main concern right now. The above should work.
I made some change in Hollfeder's code and it worked perfectly :)
-(void) start {
NSString *user = [[NSString alloc] initWithString:#"exampleuser"];
NSString *password = [[NSString alloc] initWithString:#"examplepassword"];
NSString *urlstr = [[NSString alloc] initWithFormat:#"http://myserver.com/myphpfile.php?user=%#&password=%#", user, password];
NSString *urlstr_encoded = [urlstr stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
NSURL *url = [NSURL URLWithString:urlstr_encoded];
NSData *data = [NSData dataWithContentsOfURL:url];
[self getData:data];
}

NSData needs to be updated

I am parsing HTML using hpple. so now I want my text to be updated as the user touches the next button. my code looks something like this
NSURL *ur = [NSURL URLWithString:[NSString stringWithFormat:#"%#",url.text]];
NSData *htmlData = [NSData dataWithContentsOfURL: ur];
TFHpple *xpathParser = [[TFHpple alloc] initWithHTMLData:htmlData];
NSArray *elements = [xpathParser search:#"//table[1]/tr[2]/td[2]/a/text()"]; // get the page title
TFHppleElement *element = [elements objectAtIndex:0];
NSString *h3Tag = [element content];
mi.text = h3Tag;
NSLog(#"%#",h3Tag);
[xpathParser release];
so I am kind of a new iPhone application development and fairly new to programming. So over here I think NSData needs to be updated.and yes when the user touches the next button the url also changes. so any help on that would be appreciated
thanks
Tushar
NSMutableString *tempString = [[NSMutableString alloc] initWithFormat:#"%#",url.text];
NSURL *ur =[[NSURL alloc] initWithString:tempString];
[tempString release];
NSData *htmlData = [[NSData alloc]initWithContentsOfURL:ur];
TFHpple *xpathParser = [[TFHpple alloc] initWithHTMLData:htmlData];
[ur release];
[htmlData release];
NSArray *elements = [xpathParser search:#"//table[1]/tr[2]/td[2]/a/text()"]; // get the page title
TFHppleElement *element = [elements objectAtIndex:0];
NSString *h3Tag = [element content];
mi.text = h3Tag;
NSLog(#"%#",h3Tag);
[xpathParser release];
try this code.
Thanks.