Parsing HTML Response - iPhone App - iphone

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
{
}

Related

ios web service login returns empty xml response

I'm an ios noob.. i'm developing an iphone app that uses a soap web service to do the login operation.
I read lots of similar questions but none helped me..
I copy-pasted the soap official code example, changing only the url and the request's xml in order to take username and password from two textviews. Connection is ok and i have http error 200 (not a real error..i know, so the connection is ok) but returned webData object length is 0 bytes and so i have an empty xml response..
Here is my code:
- (IBAction)actBtnLogin:(id)sender {
recordResults = NO;
NSString *soapMessage = [NSString stringWithFormat:
#"<SOAP-ENV:Envelope "
"xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\" "
"xmlns:ns1=\"urn:dbmanager\" "
"xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" "
"xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" "
"xmlns:ns2=\"http://xml.apache.org/xml-soap\" "
"xmlns:SOAP-ENC=\"http://schemas.xmlsoap.org/soap/encoding/\" "
"SOAP-ENV:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\"> "
"<SOAP-ENV:Body> "
"<ns1:camiop> "
"<strOp xsi:type=\"xsd:string\">login</strOp> "
"<strTessera xsi:type=\"xsd:string\"/> "
"<anyParametri xsi:type=\"ns2:Map\"> "
"<item> "
"<key xsi:type=\"xsd:string\">CRM_USERNAME</key> "
"<value xsi:type=\"xsd:string\">%#</value> "
"</item> "
"<item> "
"<key xsi:type=\"xsd:string\">CRM_PASSWORD</key> "
"<value xsi:type=\"xsd:string\">%#</value> "
"</item> "
"<item> "
"<key xsi:type=\"xsd:string\">CRM_SITEAPP</key> "
"<value xsi:type=\"xsd:int\">2</value> "
"</item> "
"</anyParametri> "
"</ns1:camiop> "
"</SOAP-ENV:Body> "
"</SOAP-ENV:Envelope> ", _outTxtuser.text, _outTxtpass.text];
NSLog(#"REQUEST = %#", soapMessage);
NSURL *url = [NSURL URLWithString:#"http://srvb.mysite.com/dbmgr.class.php"];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
NSString *msgLength = [NSString stringWithFormat:#"%d", [soapMessage length]];
[theRequest addValue:#"text/xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[theRequest addValue:#"srvbop" forHTTPHeaderField:#"SOAPAction"];
[theRequest addValue:msgLength forHTTPHeaderField:#"Content-Length"];
[theRequest setHTTPMethod:#"POST"];
[theRequest setHTTPBody:[soapMessage dataUsingEncoding:NSUTF8StringEncoding]];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if(theConnection)
{
//webData = [[NSMutableData data] retain];
NSLog(#"theConnection OK");
}
else
{
NSLog(#"theConnection is null");
}
}
-(void)connection:(NSURLConnection*)connection didReceiveResponse:(NSURLResponse*)response
{
[_webData setLength:0];
NSHTTPURLResponse * httpResponse;
httpResponse = (NSHTTPURLResponse *) response;
NSLog(#"HTTP error %zd", (ssize_t) httpResponse.statusCode);
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData*)data
{
[_webData appendData:data];
NSLog(#"DID RECEIVE DATA");
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError*)error
{
NSLog(#"error with the connection");
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(#"DONE. Received bytes %d", [_webData length]);
//NSString *theXML = [[NSString alloc] initWithBytes:[_webData mutableBytes] length:[_webData length] encoding:NSUTF8StringEncoding];
//NSLog(#"xml %#",theXML);
NSString *theXML = [[NSString alloc] initWithData: _webData encoding:NSUTF8StringEncoding];
_webData = nil;
NSLog(#"Response: %#", theXML);
[_outLabelrich setText:[NSString stringWithFormat:#"Response: %#", theXML]];
/*xmlParser = [[NSXMLParser alloc] initWithData:webData];
[xmlParser setDelegate:self];
[xmlParser setShouldResolveExternalEntities:YES];
[xmlParser parse];
*/
}
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict
{
if([elementName isEqualToString:#"Symbol"] || [elementName isEqualToString:#"Last"] || [elementName isEqualToString:#"Time"] )
{
if(!_soapResults)
{
_soapResults = [[NSMutableString alloc]init];
}
recordResults = YES;
}
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
if(recordResults)
{
[_soapResults appendString:string];
}
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
if([elementName isEqualToString:#"Symbol"] || [elementName isEqualToString:#"Last"] || [elementName isEqualToString:#"Time"] )
{
recordResults = NO;
NSLog(#"%#", _soapResults);
_soapResults = nil;
}
}
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
- (void)viewDidUnload {
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
-(BOOL) textFieldShouldReturn:(UITextField *)textField{
[textField resignFirstResponder];
return YES;
}
- (IBAction)backgroundClick:(id)sender {
[_outTxtuser resignFirstResponder];
[_outTxtpass resignFirstResponder];
}
thanks for the help
Sorry for not directly answering your question, but I would highly recommend against writing custom networking/parsing code when there are a number of well developed and highly tested libraries that can handle the dirty work for you. Check out AFNetworking, it will handle the dirty work of the connections and XML parsing for you, while using the convenience of blocks.
For example, here's the AFNetworking equivalent of accessing and parsing a JSON resource (substitute AFXMLRequestOperation for AFJSONRequestOperation in your case)
NSURL *url = [NSURL URLWithString:#"https://alpha-api.app.net/stream/0/posts/stream/global"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
NSLog(#"App.net Global Stream: %#", JSON);
} failure:nil];
[operation start];

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.

Send Request For Web Service And Important Delegate Methods For XML Parsing

I want to send request to service and in reply i am getting xml data.
So, please tell me how can i send request to the web-server with check of internet connection and also let me know the important delegate methods for xml parsing.
First You Also Need To get The Reachability.h and Reachability.m File
*You Can get Reachability File From here :-- *
http://developer.apple.com/library/ios/samplecode/Reachability/Reachability.zip
Also Need To import .h file in your file in which you want to check internet connection
Define below variables in your .h file
NSMutableData *urlData;
NSMutableString *currentElementValue;
Also Define the Property of NSMutableString
Below is the code for urlConnection
reachability = [Reachability reachabilityForInternetConnection];
[reachability startNotifier];
NetworkStatus remoteHostStatus = [reachability currentReachabilityStatus];
if(remoteHostStatus == NotReachable)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Alert Title"
message:#"Internet connection not currently available."
delegate:nil
cancelButtonTitle:nil
otherButtonTitles:#"Ok", nil];
[alert show];
[alert release];
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
return;
}
NSString *post = [NSString stringWithFormat:#""];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding
allowLossyConversion:NO];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:#"Your Information Which You Want To Pass"]]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
urlData=[[NSMutableData alloc] init];
[[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
For XML Parsing Below Important Methods
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[urlData setLength:0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[urlData appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
xmlParser = [[NSXMLParser alloc] initWithData:urlData];
[xmlParser setDelegate:self];
[xmlParser parse];
[urlData release];
}
#pragma mark -
#pragma mark XML Parsing Delegate Methods
- (void)parserDidStartDocument:(NSXMLParser *)parser
{
}
-(void)parserDidEndDocument:(NSXMLParser *)parser
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
}
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI
qualifiedName:(NSString *)qName
attributes:(NSDictionary *)attributeDict
{
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
NSCharacterSet *charsToTrim = [NSCharacterSet whitespaceAndNewlineCharacterSet];
string = [string stringByTrimmingCharactersInSet:charsToTrim];
if(!currentElementValue)
currentElementValue = [[NSMutableString alloc] initWithString:string];
else
[currentElementValue appendString:string];
//NSLog(#"Current Element Value :- '%#'",currentElementValue);
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
[currentElementValue release];
currentElementValue = nil;
}
You Can also abort the parsing by Below Line
[xmlParser abortParsing];
this question have already asked you should try atleast first by yourself well,
here u go for the complete solution:
to check internet connection
hope will help u!!

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.