How do i grab numbers from a Table on a website in my Cocoa App? - objective-c

Ok this is a more specific version of my last question.
So on a website there exists some data that is coded in HTML into a table.
In my Cocoa app, I want to download the html code of the website and then read through the html and snag the data from it. I was hoping someone could point out some useful classes/methods for accomplishing the retrieval of the website and putting it into some format where I can read through the code in my program?
Thanks in advance!

Try using hpple, it's an HTML parser for ObjC.
here's an example using it:
#import "TFHpple.h"
NSData *data = [[NSData alloc] initWithContentsOfFile:#"example.html"];
// Create parser
xpathParser = [[TFHpple alloc] initWithHTMLData:data];
//Get all the cells of the 2nd row of the 3rd table
NSArray *elements = [xpathParser search:#"//table[3]/tr[2]/td"];
// Access the first cell
TFHppleElement *element = [elements objectAtIndex:0];
// Get the text within the cell tag
NSString *content = [element content];
[xpathParser release];
[data release];

Related

Extracting Text from url Xcode?

I am new to Objective C.
I was trying to extract text from a webpage and display it in a textView;
Except for when I run the app it appears to show html instead of the article.
NSURL *URL = [NSURL URLWithString:[self.url
stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]];
NSData *theData = [NSData dataWithContentsOfURL:URL];
NSString *content = [[NSString alloc] initWithData:theData encoding:NSStringEncodingConversionAllowLossy];
_viewPage.text = content;
The viewPage is the textview itself. How do I extract the text only?
You have not included any code to extract the text from the web page. When you run "dataWithContentsOfURL" and it's a web page, then, as you have seen, you get the whole page.
To extract the data you need to process the results. In a simple case you can get the text with some string manipulation. In more complex cases you should look for a library which will parse the whole page for you. You can then access the parsed structure to get the content that you want.
Look here for an example of the simple case;
http://natashatherobot.com/html-css-parser-objective-c/
There are libraries for the more complex case.

How to add NSArray in a video with AVMutableMetadataItem?

I am trying to save video with custom NSArray metadata relevant for my app and trying to retrieve it when the user selects that video from the library.
I'm using the AVAssetExportSession function to add metadata.
I used the sample code AVMovieExporter, and I tried to change locationMetadata.value
http://developer.apple.com/library/ios/#samplecode/AVMovieExporter/Introduction/Intro.html#//apple_ref/doc/uid/DTS40011364
AVMutableMetadataItem *locationMetadata = [[AVMutableMetadataItem alloc] init];
locationMetadata.key = AVMetadataCommonKeyLocation;
locationMetadata.keySpace = AVMetadataKeySpaceCommon;
locationMetadata.locale = self.locale;
//locationMetadata.value = [NSString stringWithFormat:#"%+08.4lf%+09.4lf", self.location.coordinate.latitude, self.location.coordinate.longitude];
locationMetadata.value = [[NSArray alloc] initWithObjects: #"abc", #123,nil];
If I use value as a NSString there is no problem, but if I use a NSArray, it doesn't save the metadata.
Where is the problem?
Apple's documentation states:
NSString *const AVMetadataCommonKeyLocation;
I understand that to say the value must be a string, and cannot be an array.

Retrieving a specific data

I am new to xcode.. and I would love to learn about retrieving data from XML.. This is a draft code that I have been stucked with for days.. I manage to display a list of XML codes
XML CODE:
<find>
<set_number>038881</set_number>
<no_records>000138874</no_records>
<no_entries>000007000</no_entries>
</find>
However, now I have some difficulties in retrieving only the set_number from this xml... The URL I have left it blank due to confidential purposes.. so dont mind about it.. The last two codes has resulted my app to force close.. Help!!
NSString *URL = [NSString stringWithFormat:#""];
NSMutableData *receivedData = [[[NSMutableData alloc] initWithContentsOfURL:[NSURL URLWithString:URL] ]autorelease];
NSString *theRecord = [[[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding] autorelease];
NSString *path = [theRecord valueForKey: #"set_number"];
NSLog(#"File Data: %#", path);
I tried to add in this code at the bottom instead..
if ([theRecord isEqualToString:#"no_records"]){
NSLog(#"Contents of URL: %#", theRecord);
}
Then I also trying to debug my codes.. No error shown.. instead they display 0 for the output.. and I am wondering is it because my no_records is an integer?? But I have assign the record as a string.. is that why they couldnt display?
I tried to add in this code at the bottom instead..
`if ([theRecord isEqualToString:#"no_records"]){
NSLog(#"Contents of URL: %#", theRecord);
}`
Then I also trying to debug my codes.. No error shown.. instead they display 0 for the output.. and I am wondering is it because my no_records is an integer?? But I have assign the record as a string.. is that why they couldnt display?? Please help!!
To parse your XML use the NSXMLParser class.
NSString *path = [theRecord valueForKey: #"set_number"];
theRecord is a NSString instance that can not use valueForKey.
You should parse your xml string first and get the content you want from tag.
Or you should get substring in your string.

xpath Table Contents into an array

How would I use xPath under the hpple Objective-C wrapper to extract the elements out of this table. Ideally I would like to put the addresses and prices into an array or dictionary.
I have been attempting to use the hpple objective c wrapper to pull the data out of the table located here: http://www.gaspry.com/index.php?zipcode=02169&action=search but haven't succeeded in getting the correct xpath query to pull out the information. Ideally, I would like to store this information in a set of arrays one, for addresses, and one for each of the prices. I am stuck on how to retrieve all of the information from the table and am unsure that my xPath is correct
My Code Thus Far is:
- (void)viewDidLoad {
[super viewDidLoad];
//Url Information
NSString *urlAddress = #"http://www.gaspry.com/index.php?zipcode=02169&action=search";
NSURL *url = [NSURL URLWithString:urlAddress];
NSData *htmlData = [[NSData alloc] initWithContentsOfURL:url];
//Start Parsing
TFHpple *xpathParser = [[TFHpple alloc] initWithHTMLData:htmlData];
NSArray *elements = [xpathParser search:#"//tBody[tr]"]; // get the table information
TFHppleElement *element = [elements objectAtIndex:0];
NSString *bodyTag = [element content];
NSLog(#"%#", bodyTag);
[xpathParser release];
[htmlData release];
}
One advice, a search path is case sensitive so make sure you use right one.
search query for :
#"//tbody//tr[1]//td[1]"
will get you address and change column "td[#]" to access other things you may want to store.
I'm not sure but address won't be parse correctly, that is, above search query will result after
tag but won't give you content before tag.
Hope this help :D

Cocoa/Obj-C simple XML file reader - need help

I asked a question yesterday about a little app that I would like to make for OSX with Cocoa/Obj-C (Xcode).
The princip is easy:
Got an XML file like this one:
<?xml version="1.0" ?>
<Report>
<Date>20110311</Date>
<Title>The Title</Title>
<Description>Description sample<Description>
</Report>
When the app is opened, there is a window with three text fields.
When a file is loaded (File -> Open) the three text fields get the value of what is in the XML elements. For my example it will be:
TextFields 1 => 20110311TextFields 2 => The TitleTextFields 3 => Description sample
And that's it!
As you can see in my description, it's maybe easy...
But I tried a lot of things, I didn't successed :/
I'm a newbie in Cocoa developpment and there's a lot of dedicated things that I don't understand like how can I make links between CODE & GUI...
Now here is my demand:
If someone could make me an Xcode project similar to my example above, for see what's wrong with my different trys, or explain me how this app can be done (with codes examples)...
I've spend 4 long days on that project but didn't have results :(
Help... :(
Miskia
Two little things to consider:
You should definitely read into the Objective-C / Cocoa documentation.
Otherwise you will never be able to program something yourself.
In the end this will save you lots of time struggling with problems like these.
The things you ask are just the very basics of programming.
(Besides the XML part)
You should never ask people to write complete applications.
People on Stack Overflow are more then willing to help with specific problems,
but they do not work for you.
That being said, here my actual answer:
The XML code you provided contains a syntax error:
The second <Description> should be </Description>
For my example code below I used the following XML file:
<?xml version="1.0" ?>
<Report>
<Date>20110311</Date>
<Title>The Title</Title>
<Description>Description sample</Description>
</Report>
This quickly written example does everything you need.
Create a new application with XCode and open the .....AppDelegate.m file.
Simply paste the Objective-C code mentioned below within the following function:
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
// Paste Here
}
Next click 'Click build and Run'.
Select your file within the NSOpenPanel and click the open-button.
Now you should see a simple dialog with the results.
Hopefully this helps you understand how to parse the XML file.
I can imagine 4 days of struggling must be unpleasant :)
The Objective-C sample code:
NSOpenPanel *openPanel = [NSOpenPanel openPanel];
NSArray *fileTypes = [NSArray arrayWithObjects:#"xml",nil];
NSInteger result = [openPanel runModalForDirectory:NSHomeDirectory() file:nil types:fileTypes ];
if(result == NSOKButton){
NSString * input = [openPanel filename];
NSXMLDocument* doc = [[NSXMLDocument alloc] initWithContentsOfURL: [NSURL fileURLWithPath:input] options:0 error:NULL];
NSMutableArray* dates = [[NSMutableArray alloc] initWithCapacity:10];
NSMutableArray* titles = [[NSMutableArray alloc] initWithCapacity:10];
NSMutableArray* descriptions = [[NSMutableArray alloc] initWithCapacity:10];
NSXMLElement* root = [doc rootElement];
NSArray* dateArray = [root nodesForXPath:#"//Date" error:nil];
for(NSXMLElement* xmlElement in dateArray)
[dates addObject:[xmlElement stringValue]];
NSArray* titleArray = [root nodesForXPath:#"//Title" error:nil];
for(NSXMLElement* xmlElement in titleArray)
[titles addObject:[xmlElement stringValue]];
NSArray* descriptionArray = [root nodesForXPath:#"//Description" error:nil];
for(NSXMLElement* xmlElement in descriptionArray)
[descriptions addObject:[xmlElement stringValue]];
NSString * date = [dates objectAtIndex:0];
NSString * title = [titles objectAtIndex:0];
NSString * description = [descriptions objectAtIndex:0];
NSString *output = [NSString stringWithFormat:#"Date: %#\nTitle: %#\nDescription: %#", date, title, description];
NSRunAlertPanel( #"Result", output, #"OK", nil, nil );
[doc release];
[dates release];
[titles release];
[descriptions release];
}
Here some additional information:
http://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/XMLParsing/Articles/UsingParser.html
Sample project:
http://dd5.org/static/XML.zip
How to create a project like above:
- Create new project
- Add code to the header (.h) and implementation (.m) files
- Design the main window
- Finally add the correct bindings
See images below how to add the bindings (already done in the sample project).
Right-click on the App Delegate drag to the NSTextFied (Picture 1).
Release the button and select the correct entry in the ray menu (Picture 2).
Feel free to look at two easy XML parser classes I created.
http://www.memention.com/blog/2009/10/31/The-XML-Runner.html
Source with projects are available at github
https://github.com/epatel/EPXMLParsers