How do I make a label load content located on a website? - iphone

I want to make a label which indicates if a band is on tour (System of a down fyi)
So I want a label in the interface to adjust to a value given on my server.
( So it needs to extract data from a (.html) file and display it as a label. )
WebViews are messy in my opinion and a label looks better.

I'd recommend using AFNetworking - http://afnetworking.com/. It will allow you to pull data from your server.
For example, you could create an XML file containing the data that you need. Then you can parse it using NSXMLParser and do whatever you need with the data.
Example:
NSURL *feedURL = [[NSURL alloc] initWithString:#"http://yourserver.com/yourxmlfile.xml"];
NSURLRequest *feedRequest = [[NSURLRequest alloc] initWithURL:feedURL];
AFXMLRequestOperation *feedOperation = [AFXMLRequestOperation XMLParserRequestOperationWithRequest:feedRequest success:^(NSURLRequest *request, NSHTTPURLResponse *response, NSXMLParser *XMLParser) {
NSLog(#"XMLRequest successful - starting parser..");
[XMLParser setDelegate:self];
[XMLParser parse];
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, NSXMLParser *XMLParser) {
UIAlertView *connectionError = [[UIAlertView alloc] initWithTitle:#"Connection Error" message:error.localizedDescription delegate:nil cancelButtonTitle:#"Dismiss" otherButtonTitles:nil, nil];
[connectionError show];
}];
XML Example:
This is the file you will upload to your server. I use the title yourxmlfile.xml in the AFXMLRequestOperation, but call it whatever you want.
<?xml version="1.0"?>
<band>
<bandname>The Band</bandname>
<bandontour>1</bandontour>
</band>
Using NSXMLParser (delegation)
Create an ivar (in your .h) to hold the data as it is parsed.
#property (nonatomic, retain) NSString *currentProperty;
This will temporarily hold elements data, then you need to do something with it when the parser reaches didEndElement.
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict {
if ([elementName isEqualToString:#"bandontour"]) {
// found the <bandontour> tag
}
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
self.currentProperty = string;
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
if ([elementName isEqualToString:#"bandontour"]) {
// finished getting the data in <bandontour>
// do something now that you've got your data retrieved
if (self.currentProperty) int bandOnTour = self.currentProperty.intValue;
if (bandOnTour == 1) self.yourLabel.text = #"Band is on tour!";
else self.yourLabel.text = #"Not on tour.";
}
}
See NSXMLParser class reference for more information.

Related

Trying to parse xml list without parent node using NSxmlparser

I have already read about NSxmlparser. I have the following file, but I do not understand how I should do for the parser.
i Trying to parse xml list without parent node using NSxmlparser
<nodes1>
<child1>txt1</child1>
<child2>Txt2</child2>
</nodes1>
<nodes1>
<child1>Txt3</child1>
<child2>Txt4</child2>
</nodes1>
<nodes1>
<child1>Txt5</child1>
<child2>Txt6</child2>
</nodes1>
Get the file and start parsing
NSError *error;
NSString *xmlPath = [[NSBundle mainBundle] pathForResource:#"yourFile" ofType:#"xml"];
NSString* contents = [NSString stringWithContentsOfFile:xmlPath encoding:NSUTF8StringEncoding error:&error];
self.xmlData = [[NSData alloc] init];
self.xmlData = [contents dataUsingEncoding:NSUTF8StringEncoding];
self.xmlParser = [[NSXMLParser alloc] initWithData:self.xmlData];
[self.xmlParser setDelegate: self];
[self.xmlParser setShouldResolveExternalEntities: YES];
[self.xmlParser parse];
then for parsing
BOOL isValid_child1 = NO;
-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *) namespaceURI qualifiedName:(NSString *)qName attributes: (NSDictionary *)attributeDict
{
if ([elementName isEqualToString:#"child1"]) {
isValid_child1 = YES;
}
}
-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
if (isValid_child1) {
valueInChild1 = string; // string is txt1
}
-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
if ([elementName isEqualToString:#"child1"]) {
isValid_child1 = NO;
[array addObject:valueInChild1]; // to add value for child1 to an array
}
I know this is dirty ;) but it works, you can do it more flexible.

why am viewing only UIImage of last element in xml file from url in iphone

When i retrieve the XML file from URL, i can Parse all the elements from the XML file and view in log file, my parsing code looks like this,
-(id) loadXMLByURL:(NSString *)urlString{
tweets = [[NSMutableArray alloc] init];
NSURL *url = [NSURL URLWithString:urlString];
NSData *data = [[NSData alloc] initWithContentsOfURL:url];
parser = [[NSXMLParser alloc] initWithData:data];
parser.delegate = self;
[parser parse];
return self;}
-(void) parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict {
if([elementName isEqualToString:#"Products"]){
currentTweet = [egsBase alloc];}}
-(void) parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{
if([elementName isEqualToString:#"img"]){
currentTweet.img=[UIImage imageWithData: [NSData dataWithContentsOfURL: [NSURL URLWithString:currentNodeContent]]];}
if ([elementName isEqualToString:#"Products"]) {
[tweets addObject:currentTweet.img];
currentTweet = nil;
currentNodeContent = nil;}}
- (void) parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{
currentNodeContent = (NSMutableString *) [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];}
I use the class name for parsing as XmlParsing . In the controller class i had implement the class file XmlParsing as XmlParsing xmlparser; Now in viewDidLoad() function i use code like this,
- (void)viewDidLoad{
[super viewDidLoad];
xmlParser = [[XMLParsing alloc] loadXMLByURL:#"http://images.com/Products.xml"];
UIImage *currentImage = [[xmlParser tweets] objectAtIndex:0];
customimage.image = currentImage;}
Here the customimage is reference for UIImageView, Now the problem is i can get only the last element value and show in the UIImageView connected in story board (ie) for better understanding it shows only the last element image and not the previous elements i use in elements. how to solve this ? where am doing wrong. Kindly suggest me.
STRUCTURE OF XML
<Products>
<products id="1">
<img>http://images.com/images/Main_pic.png</img>
</products>
<products id="2">
<img>http://images.com/images/image1.png</img>
</products>
</Products>
My NSLog shows for parsing XML file,
images <UIImage: 0x71529a0>
images <UIImage: 0x74a6750>
When i print to check what image i get it shows the current image as,
Current,<UIImage: 0x74a6750>
here you can see the current image shows the last element alone not the previous one
- (void)viewDidLoad
{
1) [super viewDidLoad];
2) xmlParser = [[XMLParsing alloc] loadXMLByURL:#"http://images.com/Products.xml"];
3) UIImage currentImage = [[xmlParser tweets] objectAtIndex:0];
4) customimage.image = currentImage;
}
I have added line numbers for ease of understanding :
Line number 3 : You always get a new image (Am i right?)
Line number 4 : whenever u get a new image you set that image to the same
imageview(customimage) due to this previous images gets replaced
with the new one.
Ideally you should set every new image to respective image views.
If u r trying to load these images in a table view ---
Then name of image view remains same but actually the object is different so you should access the imageview of each cell by its TAG assigned in cellForRowAtIndexPath.
Updated Code
-(void) parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
if([elementName isEqualToString:#"products"])
{
currentTweet = [egsBase alloc];}}
}
-(void) parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
if([elementName isEqualToString:#"img"])
{
currentTweet.img=[UIImage imageWithData: [NSData dataWithContentsOfURL: [NSURL URLWithString:currentNodeContent]]];
[tweets addObject:currentTweet.img];
}
if ([elementName isEqualToString:#"products"])
{
currentTweet = nil;
currentNodeContent = nil;
}
}
Desc : while parsing when "products" is found as start element and object gets created, and when end element is found image gets associated to objects and gets added to array.
I see the error is : you are using "Products" in parsing condition instead of "products"
Hope the idea helps
:)
Append the string to currentnodecontent
if(!currentNodeContent )
currentNodeContent = [[NSMutableString alloc] initWithString:string];
else
[currentNodeContent appendString:string];

how to parse xml for ios development

So I know how to parse some XML structures but I am currently trying to parse this specific xml structure thats a bit different to what I am used to.
normally I would parse something like
<xml>
<data>
<name>Forrest</name>
<age>25</name>
<username>forrestgrant</username>
</data>
</xml>
But now I'm working with some xml like so..
<xml>
<data name="Forrest" age="25" username="forrestgrant" />
<other value="6" />
</xml>
how do I access those variables when they are structured like this?
This is how I would normally approach this task, which is baised of searching for the title tags and getting the data from each one.. however I am now trying to figure out how to parse this other style of xml.
- (void)startTheParsingProcess:(NSData *)parserData
{
[myDataArray release]; // clears array for next time it is used.
myDataArray = [[NSMutableArray alloc] init]; //initalizes the array
NSXMLParser *parser = [[NSXMLParser alloc] initWithData:parserData]; //incoming parserDatapassed to NSXMLParser delegate which starts parsing process
[parser setDelegate:self];
[parser parse]; //Starts the event-driven parsing operation.
[parser release];
}
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
if ([elementName isEqual:#"item"]) {
// NSLog(#"Found title!");
itemString = [[NSMutableString alloc] init];
}
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
[itemString appendString:string];
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
if ([elementName isEqual:#"item"]) {
//NSLog(#"ended title: %#", itemString);
[myDataArray addObject:itemString]; //this is where i pass the values over to my array.
[itemString release];
itemString = nil;
}
}
- (void)parserDidEndDocument:(NSXMLParser *)parser
{
// Passes myDataArray to the method that will sort and display the array into a uitableview.
[self startSortingTheArray:myDataArray];
}
any help would be greatly appreciated..
The xml data above provides the data as attributes on the xml element.
This callback method gives you access to the attributes as a dictionary of key values (attributeDict).
(void) parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI
qualifiedName:(NSString *)qualifiedName
attributes:(NSDictionary *)attributeDict
NSLog the dictionary out in that method to see the values:
NSLog(#"attributes: %#", attributeDict);
In your didStartItem: method, the attributes dictionary will contain values for all the XML attributes.

XML attribute pasrsing problem

i have to parse an xml and the link of that xml is
http://qasimshah.sitesled.com/schedule.xml
and may to parse is:
-(IBAction)autoLoginBtn{
NSString *url=[NSString stringWithFormat: #"http://qasimshah.sitesled.com/schedule.xml"];
[self parseXMLFileAtURL:url];
}
- (void)parseXMLFileAtURL:(NSString *)URL
{
xmlDataArray1 = [[NSMutableArray alloc] init];
//you must then convert the path to a proper NSURL or it won't work
NSURL *xmlURL = [NSURL URLWithString:URL];
// here, for some reason you have to use NSClassFromString when trying to alloc NSXMLParser, otherwise you will get an object not found error
// this may be necessary only for the toolchain
NSXMLParser *rssParser = [[NSXMLParser alloc] initWithContentsOfURL:xmlURL];
// Set self as the delegate of the parser so that it will receive the parser delegate methods callbacks.
[rssParser setDelegate:self];
// Depending on the XML document you're parsing, you may want to enable these features of NSXMLParser.
[rssParser setShouldProcessNamespaces:NO];
[rssParser setShouldReportNamespacePrefixes:NO];
[rssParser setShouldResolveExternalEntities:NO];
[rssParser parse];
}
-(void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError{
NSLog(#"Error on XML Parse: %#", [parseError localizedDescription] );
}
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{
//NSLog(#"found this element: %#", elementName);
currentElement = [elementName copy];
if ([elementName isEqualToString:#"Sports"]) {
// clear out our story item caches...
item = [[NSMutableDictionary alloc] init];
currentTitle = [[NSMutableString alloc] init];
}
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{
if ([elementName isEqualToString:#"Sport"]) {
[item setObject:currentTitle forKey:#"id"];
[xmlDataArray1 addObject:[item copy]];
NSLog(#"id: %#", currentTitle);
}
}
but when i try to get 'id' or name parser detect it but do not return me its value.
so how can i get its value?
You should get the attribute value in "attributeDict"
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{
you are only referring element ...
Try this. You can get all the values like this.
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI
qualifiedName:(NSString *)qName
attributes:(NSDictionary *)attributeDict
{
if([elementName isEqualToString:#"Sport"])
{
NSString *s = [NSString stringWithFormat:#"%#",elementName];
NSLog(#"%#",s);
NSString *s1 =[NSString stringWithFormat:#"%#",[attributeDict valueForKey:#"id"]];
NSLog(#"%#",s1);
NSString *s2 =[NSString stringWithFormat:#"%#",[attributeDict valueForKey:#"name"]];
NSLog(#"%#",s2);
NSString *s3 =[NSString stringWithFormat:#"%#",[attributeDict valueForKey:#"abbr"]];
NSLog(#"%#",s3);
}
}
In didStartElement: you're checking for "Sports" but in didEndElement: you're checking for "Sport"...

How to parse a locally stored XML file in iPhone?

How to parse a locally stored XML file in iPhone?
please help me with this using code snippets
I have used NSXMLParser and i achieved it. I have r.xml file in my resource. I have just parsing the title and displayed using NSXMLParser.
r.xml:
<rss>
<eletitle > My Xml Program </eletitle>
</rss>
Here my sample code is,
#interface:
NSXMLParser *rssparser;
NSMutableArray *stories;
NSMutableDictionary *item;
NSMutableString *currrentTitle;
NSString *currentElement;
#implementation:
-(void) viewDidAppear:(BOOL) animated
{
[self parseXMLFileAtURL];
}
-(void) parseXMLFileAtURL
{
stories = [[NSMutableArray alloc] init];
NSURL *xmlURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:#"r" ofType:#"xml"]];
rssparser = [[NSXMLParser alloc] initWithContentsOfURL:xmlURL];
[rssparser setDelegate:self];
[rssparser setShouldProcessNamespaces:NO];
[rssparser setShouldReportNamespacePrefixes:NO];
[rssparser setShouldResolveExternalEntities:NO];
[rssparser parse];
}
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{
currentElement = [elementName copy];
if([elementName isEqualToString:#"rss"]);
{
item = [[NSMutableDictionary alloc] init];
currrentTitle = [[NSMutableString alloc] init];
}
}
-(void) parser:(NSXMLParser *)parser foundCharacters:(NSString *) string
{
if([currentElement isEqualToString:#"eletitle"])
{
[currrentTitle appendString:string];
}
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{
if([elementName isEqualToString:#"rss"])
{
[item setObject:currrentTitle forKey:#"eletitle"];
[stories addObject:[item copy]];
}
}
- (void)parserDidEndDocument:(NSXMLParser *)parser
{
NSLog(#"The currrentTitle is %#",currrentTitle);
}
Best of Luck.
I'm sorry I cannot give you any snippet now, but in one project I did some time ago, we used the touchXML library.
http://code.google.com/p/touchcode/wiki/TouchXML
With this, parsing XML was pretty easy.
Good luck!