Failed to parse the XML iPhone - iphone

I am using the below code to parse the downloaded file, previously before restarting my mac it was working fine but now it says Failed to parse the XML, while the data need to be downloaded is being shown properly.
-(IBAction)loginButton:(id)sender{
NSString *user = [userNameField text];
NSString *passwd = [passwordField text];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:user forKey:#"Username"];
[defaults setObject:passwd forKey:#"Password"];
[defaults synchronize];
NSLog(#"Data Saved");
NSString *urlAsString = #"http";
NSURL *url = [NSURL URLWithString:urlAsString];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];
[urlRequest setTimeoutInterval:30.0f];
[urlRequest setHTTPMethod:#"POST"];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse *response,NSData *data, NSError *error) {
if ([data length] >0 && error == nil){
NSString *html = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"HTML = %#", html);
}
else if ([data length] == 0 && error == nil){
NSLog(#"Nothing was downloaded.");
}
else if (error != nil){
NSLog(#"Error happened = %#", error);
} }];
NSString *xmlFilePath = [[NSBundle mainBundle] pathForResource:#"data" ofType:#"xml"];
NSData *xml = [[NSData alloc] initWithContentsOfFile:xmlFilePath];
self.xmlParser = [[NSXMLParser alloc] initWithData:xml];
self.xmlParser.delegate = self;
if ([self.xmlParser parse]) {
NSLog(#"The XML is parsed");
}else{
NSLog(#"Failed to parse the XML");
}
}
-(void)parserDidStartDocument:(NSXMLParser *)parser {
self.rootElement = nil;
self.currentElementPointer = nil; }
-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{
if (self.rootElement == nil){
self.rootElement = [[XMLElement alloc] init]; self.currentElementPointer = self.rootElement;
} else {
XMLElement *newElement = [[XMLElement alloc] init]; newElement.parent = self.currentElementPointer; [self.currentElementPointer.subElements addObject:newElement]; self.currentElementPointer = newElement;
}
self.currentElementPointer.name = elementName; self.currentElementPointer.attributes = attributeDict;
NSString *user = [NSString stringWithFormat:#"%#", [attributeDict objectForKey:#"user"]];
NSLog(#"User: %#", user);
if ([user isEqualToString:#"1"]) {
NSLog(#"Test succeeded!");
}
}
-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{
if ([self.currentElementPointer.text length] > 0){
self.currentElementPointer.text =
[self.currentElementPointer.text stringByAppendingString:string];
} else {
self.currentElementPointer.text = string; }
}
-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{
self.currentElementPointer = self.currentElementPointer.parent;
}
-(void)parserDidEndDocument:(NSXMLParser *)parser{
self.currentElementPointer = nil;
}

On failure to parse the XML you should look at -(NSError *)parseError to see where exactly the error lies.
NSLog(#"Parse Error: %#", [self.xmlParser parseError]);
This isn't a direct answer to your question but as you have not actually asked one (?) I wouldn't know where to start other than there.

Related

NSXMLParserDelegate methods are not called

Hi iam parsing an xml file and i got the response also which i have stored in a responseString.My problem with the delegate methods which are not being called, here's my parsing code
-(void)getData
{
NSURL *url = [NSURL URLWithString:#"http://quizpro.testshell.net/api/quiz/4"];
NSData *data = [NSData dataWithContentsOfURL:url]; // Load XML data from web
NSString *applicationDocumentsDir =
[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *storePath = [applicationDocumentsDir stringByAppendingPathComponent:#"quiz.xml"];
NSLog(#"store path is %#",storePath);
[data writeToFile:storePath atomically:TRUE];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
request.delegate=self;
[request startSynchronous];
NSError *error = [request error];
if (!error)
{
NSData *responseData=[request responseData];
NSString *data =[[[NSString alloc]initWithData:responseData encoding:NSUTF8StringEncoding] autorelease];
NSString *usableXmlString = [data stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSLog(#"usableXmlString is %#",usableXmlString);
NSData *usableData = [usableXmlString dataUsingEncoding:NSUTF8StringEncoding];
NSXMLParser *xmlParser = [[NSXMLParser alloc]initWithData:usableData];
[xmlParser setDelegate:self];
[xmlParser parse];
}
}
- (void)requestFinished:(ASIHTTPRequest *)request
{
NSLog(#"requestFinished method");
// Use when fetching text
NSString *responseString = [request responseString];
** I get the entire data here **
NSLog(#"responseString is %#",responseString);
NSData *xData = [responseString dataUsingEncoding:NSUTF8StringEncoding];
//myCode.text = responseString;
//NSLog(#" response %#", responseString);
NSXMLParser *parser = [[NSXMLParser alloc] initWithData:xData];
[parser setDelegate:self];
[parser parse];
[parser release];
}
And i wrote the NSXMLParser delegate methods like below
-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
NSLog(#"parser/didStartElement");
currentTag = elementName;
if ([currentTag isEqualToString:#"questions"])
{
exams_object=[[ExamsObject alloc]init];
NSLog(#"%#",currentTag);
}
if ([currentTag isEqualToString:#"Question"])
{
exams_object=[[ExamsObject alloc]init];
}
if ([currentTag isEqualToString:#"Response"])
{
exams_object.responseArray=[[NSMutableArray alloc]init];
}
NSLog(#"%#",currentTag);
}
-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
NSLog(#"parser/didEndElement");
if ([currentTag isEqualToString:#"questions"])
{
exams_object=[[ExamsObject alloc]init];
}
if([elementName isEqualToString:#"Question"])
{
[mainArray addObject:exams_object];
}
}
-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)str
{
NSLog(#"parser/foundCharacters");
if ([currentTag isEqualToString:#"questionText"])
{
[exams_object.questionArray addObject:str];
}
if ([currentTag isEqualToString:#"responseText"])
{
[exams_object.responseArray addObject:str];
}
}
Thanks for help me
Have you included NSXMLParserDelegate and ASIHTTPRequestDelegate in your .h file ?
You are calling the method to parse the XML from delegate of ASIHTTPRequest
Check the flow of execution using breakpoints.
#interface yourClassName: NSObject <NSXMLParserDelegate, ASIHTTPRequestDelegate>
Also check these stackoverflow questions
Question 1
Question 2
Check whether you have added NSXMLParserDelegate in #interface and set parser.delegate=self in the class where you are using.

Webservices In Apple Iphone connection

Am having a webservice. Need my apple code to connect and pass 3parameters to the web service. Am very new to Objective C. Can anyone provide a sample code or guide me through this? Have searched links in StackOverflow. But not able to understand them.
Thanks In Advance.
NSString *urlString= [NSString stringWithFormat:#"http://demo.xyz.com/proj/webservices/display_records/1/%#%#%#",myid,name,password];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString]];
conn= [[NSURLConnection alloc]initWithRequest:request delegate:self];
if(conn)
{
webdata=[[NSMutableData data]retain];
}
Use defalut connection methods
You using soap message okey then akshar first you create a class of NSObject and then define a method in .h file with 3 parameter as given in below code:-
in .h file
#interface GetPartParser : NSObject <NSXMLParserDelegate>
{
NSXMLParser *xmlParser;
NSMutableArray *getPartArr;
NSMutableDictionary *item;
NSString *currentElement;
NSMutableString *part_urlStr, *partNameStr;
}
#property (nonatomic,retain) NSMutableArray *getPartArr;
-(void) fetchPartXMLData:(NSInteger)empid:(NSInteger)serid:(NSInteger)seaid:(NSInteger)episodeid;
and in .m file :-
-(void) fetchPartXMLData:(NSInteger)empid:(NSInteger)serid:(NSInteger)seaid :(NSInteger)episodeid
{
NSURL *myURL = [NSURL URLWithString:#"http://webservices.asmx"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: myURL cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
NSString *soapMessage = [NSString stringWithFormat:#"<?xml version=\"1.0\" encoding=\"utf-8\"?>"
"<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"
"<soap:Body>"
"<GetPart xmlns=\"http://tempuri.org/\">"
"<empid>%d</empid>"
"<serid>%d</serid>"
"<seaid>%d</seaid>"
"<episodeId>%d</episodeId>"
"</GetPart>"
"</soap:Body>"
"</soap:Envelope>",empid,serid,seaid,episodeid];
NSLog(#"soapMessage :%#",soapMessage);
[request addValue:#"text/xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[request addValue:#"http://tempuri.org/GetPart" forHTTPHeaderField:#"SOAPAction"];
NSString *msgLength = [NSString stringWithFormat:#"%d",[soapMessage length]];
[request addValue:msgLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPMethod: #"POST"];
[request setHTTPBody:[soapMessage dataUsingEncoding:NSUTF8StringEncoding]];
NSURLResponse *returnedResponse = nil;
NSError *returnedError = nil;
NSData *barData = [NSURLConnection sendSynchronousRequest:request returningResponse:&returnedResponse error:&returnedError];
NSString *barString = [[NSString alloc] initWithBytes:[barData bytes] length:[barData length] encoding:NSUTF8StringEncoding];
NSLog(#"barString :%#",[[barString stringByReplacingOccurrencesOfString:#"<" withString:#"<"] stringByReplacingOccurrencesOfString:#">" withString:#">"]);
NSData* data=[[[barString stringByReplacingOccurrencesOfString:#"<" withString:#"<"] stringByReplacingOccurrencesOfString:#">" withString:#">"] dataUsingEncoding:NSUTF8StringEncoding];
xmlParser = [[NSXMLParser alloc] initWithData:data];
[xmlParser setDelegate:self];
[xmlParser setShouldResolveExternalEntities:NO];
[xmlParser setShouldProcessNamespaces:NO];
[xmlParser setShouldReportNamespacePrefixes:NO];
[xmlParser parse];
}
- (void)parserDidStartDocument:(NSXMLParser *)parser
{
getPartArr =[[NSMutableArray alloc] init];
}
- (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError
{
NSString * errorString = [NSString stringWithFormat:#"Unable to download story feed from web site (Error code %i )", [parseError code]];
UIAlertView * errorAlert = [[UIAlertView alloc] initWithTitle:#"Error loading content" message:errorString delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[errorAlert show];
}
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict
{
{
currentElement = [elementName copy];
if ([elementName isEqualToString:#"part"])
{
item = [[NSMutableDictionary alloc] init];
part_urlStr = [[NSMutableString alloc]init];
partNameStr = [[NSMutableString alloc]init];
}
}
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
if ([currentElement isEqualToString:#"part_url"])
{
[part_urlStr appendString:string];
}
if ([currentElement isEqualToString:#"partName"])
{
[partNameStr appendString:string];
}
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
if ([elementName isEqualToString:#"part"])
{
[item setObject:part_urlStr forKey:#"part_url"];
[item setObject:partNameStr forKey:#"partName"];
[getPartArr addObject:[item copy]];
}
NSLog(#"item dictionary....%#",partNameStr);
}
- (void)parserDidEndDocument:(NSXMLParser *)parser
{
NSLog(#"getPartArr :%#",getPartArr);
}
it helps you and give what you want...
if you like then mark it as accepted
An event simpler way to get a ws result is:
NSString *urlString= [NSString stringWithFormat:#"http://demo.xyz.com/proj/webservices/display_records/1/%#%#%#",myid,name,password];
NSString *wsRes = [NSString stringWithContentsOfURL:urlStribng encoding: NSUTF8StringEncoding error:nil];
Consider extending this sample with error handling if you are going to use it.

issue with NSXmlparser/variable issue. - variable does not get reset

I am having an issue with one of my variables, and I cant seem to find the issue. The issue is when a user logs in, its fine, when a user logs out, it is fine. It is when the user then relogs in. The userId is kept the same.
-(IBAction)postData:(id)sender
{
cmdLoginButton.hidden = YES;
cmdLoginButton.enabled = NO;
if(textName.text.length && textNumber.text.length > 0)
{
//[self performSelectorInBackground:#selector(sendData) withObject:nil];
NSMutableData *data = [NSMutableData data];
NSString *name = textName.text;
NSString *number = textNumber.text;
NSString *nameString = [[NSString alloc] initWithFormat:#"name=%#", name];
NSString *numberString = [[NSString alloc] initWithFormat:#"&number=%#", number];
NSString *genderString = [[NSString alloc] initWithFormat:#"&gender=%#", gender];
//NSLog(nameString);
//NSLog(numberString);
[data appendData:[nameString dataUsingEncoding:NSUTF8StringEncoding]];
[data appendData:[numberString dataUsingEncoding:NSUTF8StringEncoding]];
[data appendData:[genderString dataUsingEncoding:NSUTF8StringEncoding]];
NSURL *url = [NSURL URLWithString:#"http://www.directory.net/test.php"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:data];
NSURLResponse *response;
NSError *err;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSLog(#"responseData: %#", responseData);
userData = responseData;
cmdLogoutButton.hidden = NO;
cmdLogoutButton.enabled = YES;
[self startParsingUserId];
}
else
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Text Fields Empty" message:#"One Or More Textfields Are Empty" delegate:self cancelButtonTitle:#"Cancel" otherButtonTitles:nil];
[alert show];
[alert release];
cmdLoginButton.enabled = YES;
cmdLoginButton.hidden = NO;
cmdLogoutButton.enabled = NO;
}
}
//*****************************START OF PARSER*************************
-(void)startParsingUserId;
{
NSXMLParser *idParser = [[NSXMLParser alloc] initWithData:userData];
idParser.delegate = self;
[idParser parse];
[idParser release];
}
-(void)parserDidStartDocument:(NSXMLParser *)parser
{
currentElementName = nil;
currentText = nil;
}
-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
if([elementName isEqualToString:#"usercallback"])
{
[currentIDDict release];
currentIDDict = [[NSMutableDictionary alloc] initWithCapacity:[interestingTags count]];
}
else if([interestingTags containsObject:elementName])
{
currentElementName = elementName;
currentText = [[NSMutableString alloc] init];
}
}
-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
[currentText appendString:string];
}
-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
if([elementName isEqualToString:currentElementName])
{
[currentIDDict setValue: currentText forKey: currentElementName];
}
else if([elementName isEqualToString:#"usercallback"])
{
[self.userArray addObject:currentIDDict];
}
NSLog(#"ending");
[currentText release];
currentText = nil;
}
-(void)parserDidEndDocument:(NSXMLParser *)parser
{
NSLog(#"end");
NSDictionary *rowData = [self.userArray objectAtIndex:0];
NSString *userID = [[NSString alloc] initWithFormat:#"%#", [rowData objectForKey:#"id"]];
self.userId = userID;
NSLog(#"DONE PARSING DOCUMENT");
NSLog(#"userid = %#", userId);
}
/*- (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError
{
NSLog(#"Error on XML Parse: %#", [parseError localizedDescription] );
}*/
//*****************************END OF PARSER*************************
-(IBAction)logout:(id)sender
{
NSString *userID = self.userId;
NSMutableData *data = [NSMutableData data];
NSMutableString *userString = [[NSMutableString alloc] initWithFormat:#"id=%#", userID];
//NSLog(userString);
//NSLog(numberString);
[data appendData:[userString dataUsingEncoding:NSUTF8StringEncoding]];
NSURL *url = [NSURL URLWithString:#"http://www.directory.net/offline.php"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:data];
NSURLResponse *response;
NSError *err;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSLog(#"responseData: %#", responseData);
cmdLoginButton.hidden = NO;
cmdLogoutButton.hidden = YES;
cmdLoginButton.enabled = YES;
cmdLogoutButton.enabled = NO;
}
The reason this happening more than likely is related to the following line.
NSDictionary *rowData = [self.userArray objectAtIndex:0];
Make sure to add a call to [self.userArray removeAllObjects]; to the logout method and I would recommend adding to login method but required.

parserDidEndDocument not getting called

parserDidNotEndDocument does not get called, it was working yesterday, the only thing that i think is different is i am using xcode 4 now. error getting thrown is Error on XML Parse: The operation couldn’t be completed. (NSXMLParserErrorDomain error 5.)
#implementation profileViewController
#synthesize userArray;
#synthesize userData;
#synthesize userId;
#synthesize gender;
#synthesize nameIB;
#synthesize numberIB;
#synthesize loginButton;
#synthesize logoutButton;
#synthesize activityIndicator;
/*
// The designated initializer. Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) {
// Custom initialization
}
return self;
}
*/
-(IBAction)textDone:(id)sender
{
[sender resignFirstResponder];
}
-(IBAction)genderSelection:(id)sender
{
if([sender selectedSegmentIndex] == kSwitchesSegmentIndex)
{
gender = #"Male";
//NSLog(gender);
}
else {
gender = #"Female";
//NSLog(gender);
}
}
-(IBAction)postData:(id)sender
{
loginButton.hidden = YES;
loginButton.enabled = NO;
if(nameIB.text.length && numberIB.text.length > 0)
{
//[self performSelectorInBackground:#selector(sendData) withObject:nil];
NSMutableData *data = [NSMutableData data];
NSString *number = numberIB.text;
NSString *name = nameIB.text;
NSString *nameString = [[NSString alloc] initWithFormat:#"name=%#", name];
NSString *numberString = [[NSString alloc] initWithFormat:#"&number=%#", number];
NSString *genderString = [[NSString alloc] initWithFormat:#"&gender=%#", gender];
//NSLog(nameString);
//NSLog(numberString);
[data appendData:[nameString dataUsingEncoding:NSUTF8StringEncoding]];
[data appendData:[numberString dataUsingEncoding:NSUTF8StringEncoding]];
[data appendData:[genderString dataUsingEncoding:NSUTF8StringEncoding]];
NSURL *url = [NSURL URLWithString:#"http://www.blah.net/test.php"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:data];
NSURLResponse *response;
NSError *err;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSLog(#"responseData: %#", responseData);
userData = responseData;
logoutButton.hidden = NO;
logoutButton.enabled = YES;
[self startParsingUserId];
}
else
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Text Fields Empty" message:#"One Or More Textfields Are Empty" delegate:self cancelButtonTitle:#"Cancel" otherButtonTitles:nil];
[alert show];
[alert release];
loginButton.enabled = YES;
loginButton.hidden = NO;
logoutButton.enabled = NO;
}
}
/*-(void)sendData
{
[activityIndicator startAnimating];
NSMutableData *data = [NSMutableData data];
NSString *number = numberIB.text;
NSString *name = nameIB.text;
NSString *nameString = [[NSString alloc] initWithFormat:#"name=%#", name];
NSString *numberString = [[NSString alloc] initWithFormat:#"&number=%#", number];
NSString *genderString = [[NSString alloc] initWithFormat:#"&gender=%#", gender];
//NSLog(nameString);
//NSLog(numberString);
[data appendData:[nameString dataUsingEncoding:NSUTF8StringEncoding]];
[data appendData:[numberString dataUsingEncoding:NSUTF8StringEncoding]];
[data appendData:[genderString dataUsingEncoding:NSUTF8StringEncoding]];
NSURL *url = [NSURL URLWithString:#"http://www.blah.net/test.php"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:data];
NSURLResponse *response;
NSError *err;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSLog(#"responseData: %#", responseData);
userData = responseData;
}*/
-(IBAction)logout:(id)sender
{
NSString *userID = self.userId;
NSMutableData *data = [NSMutableData data];
NSMutableString *userString = [[NSMutableString alloc] initWithFormat:#"id=%#", userID];
//NSLog(userString);
//NSLog(numberString);
[data appendData:[userString dataUsingEncoding:NSUTF8StringEncoding]];
NSURL *url = [NSURL URLWithString:#"http://www.blah.net/offline.php"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:data];
NSURLResponse *response;
NSError *err;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSLog(#"responseData: %#", responseData);
loginButton.hidden = NO;
logoutButton.hidden = YES;
loginButton.enabled = YES;
logoutButton.enabled = NO;
}
-(void)startParsingUserId
{
NSLog(#"parsing init");
NSXMLParser *idParser = [[NSXMLParser alloc] initWithData:userData]; //uses the NSMutableData data type to parse
idParser.delegate = self; //set the delegate to this viewControlelr
[idParser parse];
[idParser release];
}
-(void)parserDidStartDocument:(NSXMLParser *)parser
{
NSLog(#"parsing started");
currentElementName = nil;
currentText = nil;
}
//this is called for each xml element
-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict
{
//NSLog(#"started element");
if ([elementName isEqualToString:#"usercallback"]) //if elementName == status then start of new tweet so make new dictionary
{
[currentIDDict release];
currentIDDict = [[NSMutableDictionary alloc] initWithCapacity:[interestingTags count]]; //make dictionary with two sections
}
else if([interestingTags containsObject:elementName]) //if current element is one stored in interesting tag, hold onto the elementName and make a new string to hold its value
{
currentElementName = elementName; //hold onto current element name
currentText = [[NSMutableString alloc] init];
}
}
-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
NSLog(#"appending");
[currentText appendString:string];
}
//after each element it goes back to the parent after calling this method
-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
if([elementName isEqualToString:currentElementName])
{
[currentIDDict setValue: currentText forKey: currentElementName];
}
else if([elementName isEqualToString:#"usercallback"])
{
[self.userArray addObject:currentIDDict];
}
NSLog(#"ending");
currentText = nil;
[currentText release];
}
-(void)parserDidEndDocument:(NSXMLParser *)parser
{
NSLog(#"end");
NSDictionary *rowData = [self.userArray objectAtIndex:0];
userId = [[NSString alloc] initWithFormat:#"%#", [rowData objectForKey:#"id"]];
NSLog(#"DONE PARSING DOCUMENT");
NSLog(#"userid = %#", userId);
}
Solution for finding parse error:
- (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError
{
NSDictionary *userInfo = parseError.userInfo;
NSNumber *lineNumber = userInfo[#"NSXMLParserErrorLineNumber"];
NSNumber *errorColumn = userInfo[#"NSXMLParserErrorColumn"];
NSString *errorMessage = userInfo[#"NSXMLParserErrorMessage"];
NSLog(#"Error occured in line %# and column %#\nWith message: %#", lineNumber, errorColumn, errorMessage);
}

Parsing HTML Response - iPhone App

I'm creating an app. I'm sending the login info using HTTP POST method and the replyI'm getting from server is in HTML format. How can I parse that HTML and add different methods for succession or failure? What I'm trying to achieve is, upon login failure it should show the message using UIAlerView and upon successful login, the app should change the view with animation. :)
The code I'm using right now:
- (IBAction) loginButton: (id) sender {
indicator.hidden = NO;
[indicator startAnimating];
loginbutton.enabled = NO;
// Create the username and password string.
// username and password are the username and password to login with
NSString *postString = [[NSString alloc] initWithFormat:#"username=%#&password=%#",userName, password];
// Package the string in an NSData object
NSData *requestData = [postString dataUsingEncoding:NSASCIIStringEncoding];
// Create the URL request
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString:#"http://localhost/dologin.php"]]; // create the URL request
[request setHTTPMethod: #"POST"]; // you're sending POST data
[request setHTTPBody: requestData]; // apply the post data to be sent
// Call the URL
NSURLResponse *response; // holds the response from the server
NSError *error; // holds any errors
NSData *returnData = [NSURLConnection sendSynchronousRequest: request returningResponse:&response error:&error]; // call the URL
/* If the response from the server is a web page, dataReturned will hold the string of the HTML returned. */
NSString *dataReturned = [[NSString alloc] initWithData:returnData encoding:NSASCIIStringEncoding];
alertWithOkButton = [[UIAlertView alloc] initWithTitle:#"Status..." message:[NSString stringWithFormat:#"%#",dataReturned] delegate:self cancelButtonTitle:#"Okay" otherButtonTitles:nil];
[alertWithOkButton show];
[alertWithOkButton release];
}
What I did exactly is I used HTMLparser class. This class is very useful if you're getting response in HTML format.
-(void)startParsingForLogin:(NSString *)userIdStr Password:(NSString *)passwordStr
{
NSString *urlString = [NSString stringWithFormat:#"http://www.example.com/loginxml.php?username=%#&password=%#",userIdStr,passwordStr];
////////NSLog(#"urlString : %#",urlString);
NSURL *xmlURL = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] initWithURL:xmlURL cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30.0]autorelease];
NSURLResponse *returnedResponse = nil;
NSError *returnedError = nil;
NSData *itemData = [NSURLConnection sendSynchronousRequest:request returningResponse:&returnedResponse error:&returnedError];
//NSString *itemString = [[[NSString alloc] initWithBytes:[itemData bytes] length:[itemData length] encoding:NSUTF8StringEncoding]autorelease];
//////NSLog(#"itemString : %#",itemString);
xmlParser = [[NSXMLParser alloc] initWithData:itemData];
[xmlParser setDelegate:self];
[xmlParser parse];
}
- (void)parserDidStartDocument:(NSXMLParser *)parser
{
////////NSLog(#"parserDidStartDocument");
}
- (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError
{
////////NSLog(#"parseErrorOccurred");
NSString * errorString = [NSString stringWithFormat:#"Error (Error code %i )", [parseError code]];
UIAlertView * errorAlert = [[UIAlertView alloc] initWithTitle:#"Error loading data" message:errorString delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[errorAlert show];
[errorAlert release];
}
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes: (NSDictionary *)attributeDict
{
////NSLog(#"didStartElement");
////NSLog(#"elementName : %#",elementName);
////NSLog(#"namespaceURI : %#",namespaceURI);
////NSLog(#"qualifiedName : %#",qualifiedName);
////NSLog(#"attributeDict : %#",attributeDict);
[registerNewArr addObject:attributeDict];
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
////NSLog(#"foundCharacters");
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
/////NSLog(#"didEndElement");
}
- (void)parserDidEndDocument:(NSXMLParser *)parser
{
}