iphone xml parser error - iphone

I'm trying to implement and parsing xml document using web service in my iphone application:
Here is my Request (HTTP GET):
http://api.stlouisfed.org/fred/category?category_id=125&api_key=78da607fc8224651eca5653e65a4be5e
Response will be:
<?xml version="1.0" encoding="utf-8" ?>
<categories>
<category id="125" name="Trade Balance" parent_id="13"/>
</categories>
my testxml.h :
#import <UIKit/UIKit.h>
#interface testxmlViewController : UIViewController {
IBOutlet UILabel *lbl1;
IBOutlet UILabel *lbl2;
IBOutlet UIButton *submit;
NSMutableData *categoryData;
NSURLConnection *URLConnection;
NSMutableString *currnetCategory;
BOOL *hello;
}
#property (nonatomic, retain) NSMutableData *categoryData;
#property (nonatomic, retain) NSURLConnection *URLConnection;
#property (nonatomic, retain) NSMutableString *currnetCategory;
- (IBAction) submitClick :(id) sender;
#end
my testxml.m file:
#import "testxmlViewController.h"
#implementation testxmlViewController
#synthesize categoryData, URLConnection;
#synthesize currnetCategory;
- (IBAction) submitClick :(id) sender
{
lbl1.text = #"Submit button was clicked.";
static NSString *URLString = #"http://api.stlouisfed.org/fred/category?category_id=125&api_key=78da607fc8224651eca5653e65a4be5e";
NSURLRequest *URLRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:URLString]];
URLConnection = [[[NSURLConnection alloc] initWithRequest:URLRequest delegate:self] autorelease];
NSAssert(self.URLConnection != nil, #"Failure to create URL connection.");
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
self.categoryData = [NSMutableData data];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[categoryData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog(#"ERROR with theConenction");
[connection release];
[categoryData release];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSString *theXML = [[NSString alloc] initWithBytes: [categoryData mutableBytes] length:[categoryData length] encoding:NSUTF8StringEncoding];
NSLog(theXML);
[theXML release];
NSXMLParser *parser = [[NSXMLParser alloc] initWithData:categoryData];
if( parser )
{
[parser release];
}
parser = [[NSXMLParser alloc] initWithData: categoryData];
[parser setDelegate: self];
[parser setShouldResolveExternalEntities: YES];
[parser parse];
[connection release];
[categoryData release];
}
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
NSLog(elementName);
if ([elementName isEqualToString:#"category"])
{
lbl1.text = [attributeDict objectForKey:#"name"];
NSLog([attributeDict objectForKey:#"name"]);
//currnetCategory = [[NSMutableString alloc] init];
}
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
if (currnetCategory)
{
[currnetCategory appendString:string];
}
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
NSLog(elementName);
}
I'm getting all the values printed correctly in my **GDB :**
<?xml version="1.0" encoding="utf-8" ?>
<categories>
<category id="125" name="Trade Balance" parent_id="13"/>
</categories>
2010-03-11 10:05:57.817 testxml[16203:207] categories
2010-03-11 10:05:57.819 testxml[16203:207] category
2010-03-11 10:05:57.822 testxml[16203:207] Trade Balance
2010-03-11 10:05:57.823 testxml[16203:207] category
2010-03-11 10:05:57.823 testxml[16203:207] categories
But it was terminating application after execution of didEndElement method.
Will you please help me to solve this problem.
Thanks.

view-source: http://api.stlouisfed.org/fred/category?category_id=125&api_key=78da607fc8224651eca5653e65a4be5e
only shows
<categories>
<category id="125" name="Trade Balance" parent_id="13"/>
</categories>
Probably not the cause but an observation anyway :-)

Related

xcode 4.2 Loop Through XML Data Elements

I am very confused on how I am supposed to loop through XML elements for my current iPhone app project. I will show my code, then clarify my question.
Here is sample XML I am using:
<restaurant_details>
<total_results>90</total_results>
<restaurant>
<name>Through the Garden</name>
<distance_from_current_location>0.55</distance_from_current_location>
<restaurant_id>123</restaurant_id>
<longitude>-84.373734</longitude>
<latitude>39.258606</latitude>
<address>10738 Kenwood Rd | cincinnati ,OH | 45242</address>
<phone_number>513-791-2199</phone_number>
<restaurant_type>General</restaurant_type>
</restaurant>
</restaurant_details>
Getting data for my table:
- (void)get_table_data {
NSString *day = [self dateInFormat:#"%A"];
NSLog (#"At get_table_data");
NSURLRequest *theRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://www.url.com"] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if (theConnection) {
NSLog (#"At connection");
receivedData = [NSMutableData data];
}
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[receivedData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[receivedData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection {
// NSString *theXML = [[NSString alloc] initWithBytes: [myWebData mutableBytes] length:[myWebData length] encoding:NSUTF8StringEncoding];
// NSLog(#"%#",theXML);[theXML release];
if(parser){
parser = nil;
}
parser = [[NSXMLParser alloc] initWithData: receivedData];
[parser setDelegate: self];
[parser setShouldResolveExternalEntities: YES];
[parser parse];
}
And my parser code:
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict{
NSLog (#"At parser");
currentElement = elementName;
if ([currentElement isEqualToString:#"restaurant_details"]) {
if ([currentElement isEqualToString:#"total_results"]) {
//NSLog(#"Element: %#", currentElement);
}else if ([currentElement isEqualToString:#"restaurant"]) {
restaurantObj = [[DOR_RestaurantClass alloc]init];
}
}
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{
if([currentElement isEqualToString:#"name"]) {
restaurantObj.name=[NSString stringWithFormat:#"%#",string];
//NSLog(#"Name to be saved in Array :- %#",string);
}
if([currentElement isEqualToString:#"distance_from_current_location"]) {
restaurantObj.distance=[NSString stringWithFormat:#"%#",string];
//NSLog(#"Name to be saved in Array :- %#",string);
}
if([currentElement isEqualToString:#"restaurant_id"]) {
restaurantObj.restId=[NSString stringWithFormat:#"%#",string];
//NSLog(#"Name to be saved in Array :- %#",string);
}
if([currentElement isEqualToString:#"address"]) {
NSArray *stringArray = [string componentsSeparatedByString:#" | "];
restaurantObj.address=[stringArray objectAtIndex:0];
restaurantObj.address2=[stringArray objectAtIndex:1];
restaurantObj.address3=[stringArray objectAtIndex:2];
//NSLog(#"Name to be saved in Array :- %#",string);
}
if([currentElement isEqualToString:#"phone_number"]) {
restaurantObj.phone=[NSString stringWithFormat:#"%#",string];
//NSLog(#"Name to be saved in Array :- %#",string);
}
if([currentElement isEqualToString:#"description"]) {
restaurantObj.description=[NSString stringWithFormat:#"%#",string];
//NSLog(#"Name to be saved in Array :- %#",string);
}
if([currentElement isEqualToString:#"image_url"]) {
restaurantObj.image=[NSString stringWithFormat:#"%#",string];
//NSLog(#"Name to be saved in Array :- %#",string);
}
if([currentElement isEqualToString:#"restaurant_type"]) {
//restaurantObj.Name=[NSString stringWithFormat:#"%#",string];
//NSLog(#"Name to be saved in Array :- %#",string);
}
NSLog (#"At parser2");
if(!currentElementValue)
currentElementValue=[[NSMutableString alloc] initWithString:string];
else
[currentElementValue appendString:string];
NSLog(#"the parser just found this text in a tag:%#",string);
}
-(void)parser:(NSXMLParser*)parser didEndElement:(NSString*)elementName namespaceURI:(NSString*)namespaceURI qualifiedName:(NSString*)qualifiedName {
NSLog(#"Current element in End Element Category:- %#",currentElement);
if([elementName isEqualToString:#"restaurant"]) {
[listItems addObject:restaurantObj];
NSLog(#"Array: %#", listItems);
}else{
currentElementValue=nil;
}
}
Here's my .h for my restaurant class:
#import <Foundation/Foundation.h>
#interface DOR_RestaurantClass : NSObject
#property (nonatomic, retain) NSString *restId;
#property (nonatomic, retain) NSString *image;
#property (nonatomic, retain) NSString *name;
#property (nonatomic, retain) NSString *description;
#property (nonatomic, retain) NSString *distance;
#property (nonatomic, retain) NSString *address;
#property (nonatomic, retain) NSString *address2;
#property (nonatomic, retain) NSString *address3;
#property (nonatomic, retain) NSString *phone;
#property (nonatomic, retain) NSString *expires;
#end
And my .m:
#import "DOR_RestaurantClass.h"
#implementation DOR_RestaurantClass
#synthesize restId;
#synthesize image;
#synthesize name;
#synthesize description;
#synthesize distance;
#synthesize address;
#synthesize address2;
#synthesize address3;
#synthesize phone;
#synthesize expires;
#end
I am getting my data and so forth, so that's not an issue. My question is this: With multiple "restaurant" tags in my XML data, how do I sort through the XML so that I keep restaurant data together? I come from PHP, so I would have done a foreach on the restaurant tags, but I'm not sure how the NSXMLParser is supposed to keep the data seperated. I will be putting this information into an NSMutableArray in the end. I just don't know where to start, and cannot find any good examples on doing this. Any and all help is greatly appreciated.
This has been updated
My array listItems (NSMutableArray) is null when I print it to NSLog.
Firstly Create a Obj c class having .h and .m files only. and in that create some NSString Variables having properties like name, distance, longitude, latitude.. etc etc.
now, the code part :-
In didStartElement
in restaurant tag create a Object of that class which i just told u to create(initialize the Object):-
currentElement = elementName;
if([currentElement isEqualToString:#"restaurant"]) {
classObj = [[MyRestaurentClass alloc]init];
}
Now In foundCharacters find the other tags like this :-
if([currentElement isEqualToString:#"name"]) {
classObj.Name=[NSString stringWithFormat:#"%#",string];
NSLog(#"Name to be saved in Array :- %#",string);
}
if ( [currentElement isEqualToString:#"longitude"])
{
classObj.longitude =[NSString stringWithFormat:#"%#",string];
}
}
Now Last part in didEneElement :-
Create a MutubaleArray in Parser Class and Add the classObj in that array in didEndElement :-
if([elementName isEqualToString:#"restaurent"]) {
NSLog(#"Current element in End Element Category:- %#",currentElement);
[ObjectsMutableArray addObject:classObj];
}
And that's all. u r finished with parsing ..
UPDATE
Firstly you dont have to write like this in If loop i.e. :-
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict{
NSLog (#"At parser");
currentElement = elementName;
if ([currentElement isEqualToString:#"restaurant_details"]) {
if ([currentElement isEqualToString:#"total_results"]) {
//NSLog(#"Element: %#", currentElement);
}else if ([currentElement isEqualToString:#"restaurant"]) {
restaurantObj = [[DOR_RestaurantClass alloc]init];
}
}
}
What i wrote in answer for didStartElement is Sufficient as didStartElement is called for Each n Every Tag.
See Once u create a class having NSStrings acc to your XML. Just create an Object of that class and Initialize it in didStartElement.
in foundCharacters you will add the Required data in the classObject variables according to the If Conditions loops. Whenever the XMlParser comes in the </restaurent> Tag it will go in didEndElement method and there you just have to Put that classObject (object) in that Array like i did in didEndElement.
Ok Regarding your NSMutableArray, have you Initialized the Array in didStartDocument like this :-
(void)parserDidStartDocument:(NSXMLParser *)parser{
listItems = [[NSMutableArray alloc]init];
}
I have Changed a Above Code so please read again the whole answer carefully.
If u still have any doubts Text me...

XMLParser Advice

I'm not sure what I am doing wrong. I have a URL leading to an XML tree that looks like:
<result>
...
<title>
...
</title>
<body>
...
</body>
...
</result>
I just need to parse the file and get the title and body. Here is my object.h:
#import <Foundation/Foundation.h>
#interface Object : NSObject
{
NSString *title;
NSString *description;
}
#property (nonatomic, retain) NSString *title;
#property (nonatomic, retain) NSString *description;
#end
And here is Object.m:
#import "Object.h"
#implementation Object
#synthesize title, description;
-(void) dealloc
{
[title release];
[description release];
[super dealloc];
}
#end
Here is my XMLParser.h:
#import <Foundation/Foundation.h>
#import "Object.h"
#interface XMLParser : NSObject <NSXMLParserDelegate>
{
NSMutableString *currentNodeContent;
NSMutableArray *arrayOfObjects;
NSXMLParser *parser;
Object *currentObject;
}
#property (readonly, retain) NSMutableArray *arrayOfObjects;
-(id) loadXMLbyURL:(NSString *)urlString;
#end
And finally, XMLParser.m:
#import "XMLParser.h"
#import "Object.h"
#implementation XMLParser
#synthesize arrayOfObjects;
-(id) loadXMLbyURL:(NSString *)urlString
{
arrayOfObjects = [[NSMutableArray alloc] init];
NSURL *url = [NSURL URLWithString:urlString];
NSData *data = [[[NSData alloc] initWithContentsOfURL:url] autorelease];
parser = [[NSXMLParser alloc] initWithData:data];
parser.delegate = self;
[parser parse];
return self;
}
-(void) dealloc
{
[parser release];
[super dealloc];
}
-(void) parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
if([elementName isEqualToString:#"result"])
{
currentObject = [Object alloc];
}
}
-(void) parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
if([elementName isEqualToString:#"title"])
{
currentObject.title = currentNodeContent;
}
if([elementName isEqualToString:#"body"])
{
currentObject.description = currentNodeContent;
}
if([elementName isEqualToString:#"result"])
{
[arrayOfObjects addObject:currentObject];
[currentObject release];
currentObject = nil;
[currentNodeContent release];
currentNodeContent = nil;
}
}
-(void) parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
currentNodeContent = (NSMutableString *) [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}
#end
In my main code I make a call to XML parser like this:
xmlParser = [[XMLParser alloc] loadXMLbyURL:#"www.websiteWithXML.com"];
However nothing is being placed into my arrayOfObjects (I know this because when I tell a tableview to have as many rows as my array, there are no rows).
please help!!! Thank you in advance!
Not sure if this will help...
Try changing:
arrayOfObjects = [[NSMutableArray alloc] init];
To:
arrayOfObjects = [[NSMutableArray alloc] initWithCapacity:0];
Other than that it appears that your code is fine. Also just because your table isn't loading anything doesn't mean that you do not have objects in your array. Use breakpoints to take a look at your data after you finish parsing and before you try to load your tableview.
Try resetting currentNodeContent inside each of your element starts. For example:
-(void) parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
if([elementName isEqualToString:#"result"])
{
currentObject = [Object alloc];
}
else if ([elementName isEqualToString:#"title"] || [elementName isEqualToString:#"body"])
{
[currentNodeContent setString:#""];
}
}
Then, when you receive characters do an append:
-(void) parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
[currentNodeContent appendString:[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]];
}
By doing this, you handle the situation where a foundCharacters gets multiple times to capture all of the characters within a given element.

How can i check that my data is attached with the RequestBody in Post method in Objective C

I making an Login Page for an app. the Credential details are stored in a DB. so i am making an ASP.Net middleware service.
Now previously i was doing GET method to send request which appends the details in URL STRING(which i dont want now).I want to do the POST method. so i found one Very good link for that, but i am not sure that whether i have done it correctly or not OR my ASP.net Colleague has done some mistake as it is not working.
If the Credentials i.e Username and Password are correct the Service returns me an XML like this
<result>
success
</result>
or failure if not.
So can any one please tell me that whether this code is correct or not and if not what is the Mistake.... Thanks For your time.
Code: -
#class FirstViewController;
#interface TestLoginViewController : UIViewController<UITextFieldDelegate,NSXMLParserDelegate>{
IBOutlet UITextField *txtUserName,*txtPassword;
IBOutlet UIButton *submitDetails;
FirstViewController *viewController;
NSString *currentElement,*status;
NSString *loginName,*password;
}
#property (nonatomic,retain) IBOutlet UITextField *txtUserName;
#property (nonatomic,retain) IBOutlet UITextField *txtPassword;
#property (retain) NSString *loginName;
#property (retain) NSString *password;
#property (retain) NSString *status;
-(IBAction)onTapSubmit:(id)sender;
-(IBAction)onTapReset;
#end
-(IBAction)onTapSubmit:(id)sender{
NSLog(#"UserName :- %#",txtUserName.text);
NSLog(#"Password :- %#",txtPassword.text);
if(![txtUserName.text isEqualToString:#""] && ![txtPassword.text isEqualToString:#""]){
// NSString *uName = txtUserName.text;
// NSString *uPass = txtPassword.text;
// NSString *post = [NSString stringWithFormat:#"username=%#&password=%#",[self urlEncodeValue:uName],[self urlEncodeValue:uPass]];
NSString *temp1 = [#"username=" stringByAppendingString:txtUserName.text];
NSString *temp2 = [temp1 stringByAppendingString:#"&password="];
NSString *post = [temp2 stringByAppendingString:txtPassword.text];
NSLog(#"Post String ==== %#",post);
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:#"http://iphonewebserver.wsisites.net/Default.aspx"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSXMLParser *parser= [[NSXMLParser alloc]initWithData:postData];
**EDITED :-**
NSURLResponse *response;
NSError *error;
NSData *urlData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSLog(#"Succeeded! Received %d bytes of data",[urlData length]);
NSString *outputdata = [[NSString alloc] initWithData:urlData encoding:NSASCIIStringEncoding];
NSLog(#"%#", outputdata);
**//Nslog output
Succeeded! Received 39 bytes of data
2011-12-14 21:28:21.461 TestLogin[1094:207] <result><login>success</login></result>
2011-12-14 21:28:21.463 TestLogin[1094:207] Status======= (null)**
/*
NSMutableString *strURL=[[NSMutableString alloc] init];
[strURL appendFormat:#"http://iphonewebserver.wsisites.net/Default.aspx?username="];
[strURL appendFormat:#"%#",txtUserName.text];
[strURL appendFormat:#"&password="];
[strURL appendFormat:#"%#",txtPassword.text];
NSLog(#"urlformed:-%#",strURL);
NSURL *url= [NSURL URLWithString:strURL];
NSData *data= [NSData dataWithContentsOfURL:url];
[strURL release];
NSXMLParser *parser= [[NSXMLParser alloc]initWithData:data];
*/
parser.delegate=self;
[parser parse];
[parser release];
// if([self.status isEqualToString:#"success"]){
if(self.status){
viewController = [[FirstViewController alloc]initWithNibName:#"FirstViewController" bundle:nil];
[self presentModalViewController:viewController animated:YES];
}
else {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Login Failed !!! " message:#"Please Enter Correct Username and Password" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
NSLog(#"%#",self.status);
}
}
else{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Login Failed !!! " message:#"Please Enter the Username and Password" delegate:self cancelButtonTitle:nil otherButtonTitles:#"OK",nil];
[alert show];
[alert release];
}
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
if(buttonIndex == 0)
{
[self onTapReset];
}
}
- (void)viewDidLoad
{
[super viewDidLoad];
txtUserName.delegate = self;
txtPassword.delegate = self;
txtUserName.text = #"admin";
txtPassword.text = #"pass";
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{
currentElement = elementName;
if([elementName isEqualToString:#"result"]) {
NSLog(#"%#",currentElement);
}
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{
if([currentElement isEqualToString:#"login"]){
self.status=[NSString stringWithFormat:#"%#",string];
NSLog(#"%#",self.status);
}
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{
currentElement=#"";//required to reset current element
}
#end
If anything i am missing to post please tell me. :))
You have created the request, but you're not sending it anywhere.
Instantiate a NSURLConnection object using your request - that will send it to the server and report the results back to it's delegate.
Finally i got my code works, as usually i was doing a very Basic mistake.... I was not giving the parser correct data to parse.... this is the code all working fine and Good.
CODE :-
#class FirstViewController;
#interface TestLoginViewController : UIViewController<UITextFieldDelegate,NSXMLParserDelegate>{
IBOutlet UITextField *txtUserName,*txtPassword;
IBOutlet UIButton *submitDetails;
FirstViewController *viewController;
NSString *currentElement,*status;
NSString *loginName,*password;
}
#property (nonatomic,retain) IBOutlet UITextField *txtUserName;
#property (nonatomic,retain) IBOutlet UITextField *txtPassword;
#property (retain) NSString *loginName;
#property (retain) NSString *password;
#property (retain) NSString *status;
-(IBAction)onTapSubmit:(id)sender;
-(IBAction)onTapReset;
#end
-(IBAction)onTapSubmit:(id)sender{
NSLog(#"UserName :- %#",txtUserName.text);
NSLog(#"Password :- %#",txtPassword.text);
if(![txtUserName.text isEqualToString:#""] && ![txtPassword.text isEqualToString:#""]){
NSString *temp1 = [#"username=" stringByAppendingString:txtUserName.text];
NSString *temp2 = [temp1 stringByAppendingString:#"&password="];
NSString *post = [temp2 stringByAppendingString:txtPassword.text];
NSLog(#"Post String ==== %#",post);
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:#"http://iphonewebserver.wsisites.net/Default.aspx"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSURLResponse *response;
NSError *error;
NSData *urlData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSLog(#"Succeeded! Received %d bytes of data",[urlData length]);
NSString *outputdata = [[NSString alloc] initWithData:urlData encoding:NSASCIIStringEncoding];
NSLog(#"%#", outputdata);
NSXMLParser *parser= [[NSXMLParser alloc]initWithData:urlData];
parser.delegate=self;
[parser parse];
[parser release];
if([self.status isEqualToString:#"success"]){
viewController = [[FirstViewController alloc]initWithNibName:#"FirstViewController" bundle:nil];
[self presentModalViewController:viewController animated:YES];
}
else {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Login Failed !!! " message:#"Please Enter Correct Username and Password" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
NSLog(#"%#",self.status);
}
}
else{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Login Failed !!! " message:#"Please Enter the Username and Password" delegate:self cancelButtonTitle:nil otherButtonTitles:#"OK",nil];
[alert show];
[alert release];
}
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
if(buttonIndex == 0)
{
[self onTapReset];
}
}
- (void)viewDidLoad
{
[super viewDidLoad];
txtUserName.delegate = self;
txtPassword.delegate = self;
txtUserName.text = #"admin";
txtPassword.text = #"pass";
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{
currentElement = elementName;
if([elementName isEqualToString:#"result"]) {
NSLog(#"%#",currentElement);
}
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{
if([currentElement isEqualToString:#"login"]){
self.status=[NSString stringWithFormat:#"%#",string];
NSLog(#"%#",self.status);
}
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{
currentElement=#"";//required to reset current element
}
#end
So Enjoy the Code and have fun.... :))

NSXMLParser Issue

I have an xml file I am parsing.
NSURL *url = [NSURL URLWithString:#"url.xml"];
NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60];
self.downloadData = [[NSMutableData alloc] initWithLength:0];
self.connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];
I have all the connections working and I thought I had the parsing working but I am having issues and do not know what I am doing wrong.
my didStartElement:
-(void) parser:(NSXMLParser *) parser didStartElement:(NSString *) elementName namespaceURI:(NSString *) namespaceURI qualifiedName:(NSString *) qName attributes:(NSDictionary *) attributeDict {
if ([elementName isEqualToString:kimgurl])
{
elementFound = YES;
}
}
foundCharacter:
-(void)parser:(NSXMLParser *) parser foundCharacters:(NSString *)string {
if (elementFound == YES) {
if(!currentValue)
{
currentValue = [[NSMutableString alloc] init];
}
[currentValue appendString: string];
}
}
then didEndElement:
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
if (elementFound) {
if ([elementName isEqualToString:kimgurl]) {
NSLog(#"imgurl: %#", currentValue);
imageItems.imageURL = currentValue;
NSLog(#"elname: %#", elementName);
NSLog(#"img: %#", kimgurl);
[currentValue setString:#""];
NSLog(#"imageitem: %#", imageItems.imageURL);
}
}
}
I have the NSLogs there because imageItems.imageURL is null. This is a class file that is like this.
ImageItems.h
#interface ImageItems : NSObject {
//parsed data
NSString *imageURL;
}
#property (nonatomic, retain) NSString *imageURL;
#end
ImageItems.m
#import "ImageItems.h"
#implementation ImageItems
#synthesize imageURL;
-(void)dealloc
{
[imageURL release];
[super dealloc];
}
#end
As you can tell by my code I am new to objective-c.
currentValue has the value Im looking for. Why is imageItems null? What am I missing?
I don't see the assignment of "imageItems" anywhere in your code. You probably need to assign it to an instance of ImageItems at some point. Perhaps with self.imageItems = [[[ImageItems alloc] init] autorelease] or imageItems = [[ImageItems alloc] init];?

RSS Reader error

I am currently doing an application which make use of the RSS Feed from http://www.learnerstogether.net/. However i keep getting the error unable to download the XML data from the website. Can someone tell me what is wrong.
#implementation Parser
#synthesize items, responseData;
#synthesize currentTitle;
#synthesize currentDate;
#synthesize currentSummary;
#synthesize currentLink;
#synthesize currentPodcastLink;
- (void)parseRssFeed:(NSString *)url withDelegate:(id)aDelegate {
[self setDelegate:aDelegate];
responseData = [[NSMutableData data] retain];
NSURL *baseURL = [[NSURL URLWithString:url] retain];
NSURLRequest *request = [NSURLRequest requestWithURL:baseURL];
[[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[responseData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[responseData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSString * errorString = [NSString stringWithFormat:#"Unable to download xml data (Error code %i )", [error code]];
UIAlertView * errorAlert = [[UIAlertView alloc] initWithTitle:#"Error loading content" message:errorString delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[errorAlert show];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
self.items = [[NSMutableArray alloc] init];
NSXMLParser *rssParser = [[NSXMLParser alloc] initWithData:responseData];
[rssParser setDelegate:self];
[rssParser parse];
}
#pragma mark rssParser methods
- (void)parserDidStartDocument:(NSXMLParser *)parser {
}
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{
currentElement = [elementName copy];
if ([elementName isEqualToString:#"item"]) {
item = [[NSMutableDictionary alloc] init];
self.currentTitle = [[NSMutableString alloc] init];
self.currentDate = [[NSMutableString alloc] init];
self.currentSummary = [[NSMutableString alloc] init];
self.currentLink = [[NSMutableString alloc] init];
self.currentPodcastLink = [[NSMutableString alloc] init];
}
// podcast url is an attribute of the element enclosure
if ([currentElement isEqualToString:#"enclosure"]) {
[currentPodcastLink appendString:[attributeDict objectForKey:#"url"]];
}
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{
if ([elementName isEqualToString:#"item"]) {
[item setObject:self.currentTitle forKey:#"title"];
[item setObject:self.currentLink forKey:#"link"];
[item setObject:self.currentSummary forKey:#"summary"];
[item setObject:self.currentPodcastLink forKey:#"podcastLink"];
// Parse date here
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat:#"E, d LLL yyyy HH:mm:ss Z"]; // Thu, 18 Jun 2010 04:48:09 -0700
NSDate *date = [dateFormatter dateFromString:self.currentDate];
[item setObject:date forKey:#"date"];
[items addObject:[item copy]];
}
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{
if ([currentElement isEqualToString:#"title"]) {
[self.currentTitle appendString:string];
} else if ([currentElement isEqualToString:#"link"]) {
[self.currentLink appendString:string];
} else if ([currentElement isEqualToString:#"description"]) {
[self.currentSummary appendString:string];
} else if ([currentElement isEqualToString:#"pubDate"]) {
[self.currentDate appendString:string];
NSCharacterSet* charsToTrim = [NSCharacterSet characterSetWithCharactersInString:#" \n"];
[self.currentDate setString: [self.currentDate stringByTrimmingCharactersInSet: charsToTrim]];
}
}
- (void)parserDidEndDocument:(NSXMLParser *)parser {
if ([_delegate respondsToSelector:#selector(receivedItems:)])
[_delegate receivedItems:items];
else
{
[NSException raise:NSInternalInconsistencyException
format:#"Delegate doesn't respond to receivedItems:"];
}
}
#pragma mark Delegate methods
- (id)delegate {
return _delegate;
}
- (void)setDelegate:(id)new_delegate {
_delegate = new_delegate;
}
- (void)dealloc {
[items release];
[responseData release];
[super dealloc];
}
#end
Your error has absolutely nothing to do with the RSS parsing aspect of this. What's more, you haven't even pasted in the full error. You should log the error object itself in your implementation of -connection:didFailWithError:. That should give you a human-readable description of what went wrong.