parserDidEndDocument not getting called - iphone

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);
}

Related

Load Web-Content Asynchronously

I am trying to load web content asynchronously. I have a large amount of web calls in my viewdidappear method and my app is very unresponsive. I understand the concepts of synchronous and asynchronous loading of content, but don't know how to tell if this is being done asynchronously. The code below is simply embedded in my viewdidappear method, and I assume it is loading synchronously. How would I edit this to make it load asynchronously? Thank you all!
NSString *strURLtwo = [NSString stringWithFormat:#"http://website.com/json.php?
id=%#&lat1=%#&lon1=%#",id, lat, lon];
NSData *dataURLtwo = [NSData dataWithContentsOfURL:[NSURL URLWithString:strURLtwo]];
NSArray *readJsonArray = [NSJSONSerialization JSONObjectWithData:dataURLtwo options:0
error:nil];
NSDictionary *element1 = [readJsonArray objectAtIndex:0];
NSString *name = [element1 objectForKey:#"name"];
NSString *address = [element1 objectForKey:#"address"];
NSString *phone = [element1 objectForKey:#"phone"];
You can use NSURLConnectionDelegate:
// Your public fetch method
-(void)fetchData
{
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"http://website.com/json.php?id=%#&lat1=%#&lon1=%#",id, lat, lon]];
// Put that URL into an NSURLRequest
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
// Create a connection that will exchange this request for data from the URL
connection = [[NSURLConnection alloc] initWithRequest:req
delegate:self
startImmediately:YES];
}
Implement the delegate methods:
- (void)connection:(NSURLConnection *)conn didReceiveData:(NSData *)data
{
// Add the incoming chunk of data to the container we are keeping
// The data always comes in the correct order
[jsonData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)conn
{
// All data is downloaded. Do your stuff with the data
NSArray *readJsonArray = [NSJSONSerialization jsonData options:0 error:nil];
NSDictionary *element1 = [readJsonArray objectAtIndex:0];
NSString *name = [element1 objectForKey:#"name"];
NSString *address = [element1 objectForKey:#"address"];
NSString *phone = [element1 objectForKey:#"phone"];
jsonData = nil;
connection = nil;
}
// Show AlertView if error
- (void)connection:(NSURLConnection *)conn didFailWithError:(NSError *)error
{
connection = nil;
jsonData = nil;
NSString *errorString = [NSString stringWithFormat:#"Fetch failed: %#", [error localizedDescription]];
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Error" message:errorString delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alertView show];
}
For asynchronous web content loading, I recommend you to use AFNetworking . It'll solve lots of your major headache of networking in future. How to do:
1) subclass AFHTTPCLient, for example:
//WebClientHelper.h
#import "AFHTTPClient.h"
#interface WebClientHelper : AFHTTPClient{
}
+(WebClientHelper *)sharedClient;
#end
//WebClientHelper.m
#import "WebClientHelper.h"
#import "AFHTTPRequestOperation.h"
NSString *const gWebBaseURL = #"http://whateverBaseURL.com/";
#implementation WebClientHelper
+(WebClientHelper *)sharedClient
{
static WebClientHelper * _sharedClient = nil;
static dispatch_once_t oncePredicate;
dispatch_once(&oncePredicate, ^{
_sharedClient = [[self alloc] initWithBaseURL:[NSURL URLWithString:gWebBaseURL]];
});
return _sharedClient;
}
- (id)initWithBaseURL:(NSURL *)url
{
self = [super initWithBaseURL:url];
if (!self) {
return nil;
}
[self registerHTTPOperationClass:[AFHTTPRequestOperation class]];
return self;
}
#end
2) Request asynchronously your web content, put this code in any relevant part
NSString *testNewsURL = #"http://whatever.com";
NSURL *url = [NSURL URLWithString:testNewsURL];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFHTTPRequestOperation *operationHttp =
[[WebClientHelper sharedClient] HTTPRequestOperationWithRequest:request success:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSString *szResponse = [[[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding] autorelease];
NSLog(#"Response: %#", szResponse );
//PUT your code here
}
failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
NSLog(#"Operation Error: %#", error.localizedDescription);
}];
[[WebClientHelper sharedClient] enqueueHTTPRequestOperation:operationHttp];

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.

NSXMLParser in model class gives me no result

I have a separate class for parsing XML I am getting from server. Here is my model class :
#import "CheckLoginModel.h"
#import "Common.h"
#import "Utils.h"
#import "Constants.h"
#implementation CheckLoginModel
#synthesize strUserID;
#synthesize strUserName;
#synthesize i;
#synthesize dict;
-(void)CheckLogin:(NSString *)strDeviceToken
{
dict = [[NSMutableDictionary alloc]init];
#try
{
NSString *soapMessage = [NSString stringWithFormat:
#"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<soapenv:Envelope \n"
"xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" \n"
"xmlns:tem=\"http://tempuri.org/\"> \n"
"<soapenv:Header/>\n"
"<soapenv:Body>\n"
"<tem:CheckDeviceToken>\n"
"<tem:dt>%#</tem:dt>\n"
"</tem:CheckDeviceToken>\n"
"</soapenv:Body>\n"
"</soapenv:Envelope>\n",strDeviceToken];
NSURL *url = [NSURL URLWithString:kMainURL];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
NSString *msgLength = [NSString stringWithFormat:#"%d", [soapMessage length]];
[theRequest addValue: #"text/xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[theRequest addValue: #"http://tempuri.org/IService1/CheckDeviceToken" 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];
}
else
{
NSLog(#"The Connection is NULL");
}
}#catch (NSException *ex) {
[Utils LogExceptionOnServer:#"ChatApplicationAppDelegate" methodName:#"CheckLogin" exception:[ex description]];
}
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[webData setLength: 0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[webData appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(#"ERROR with theConenction");
[connection release];
[webData release];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(#"DONE. Received Bytes: %d", [webData length]);
NSString *theXML = [[NSString alloc] initWithBytes: [webData mutableBytes] length:[webData length] encoding:NSUTF8StringEncoding];
NSLog(#"%#",theXML);
[theXML release];
NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithData: webData];
[xmlParser setDelegate:self];
[xmlParser setShouldResolveExternalEntities: YES];
[xmlParser parse];
[xmlParser release];
[connection release];
[webData release];
//if(strUserName != NULL)
[[NSNotificationCenter defaultCenter] postNotificationName:#"register" object:self userInfo:dict];
//[dict release];
}
#pragma mark -
#pragma mark XML PARSING RELATED FUNCTIONS
#pragma mark -
-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *) namespaceURI qualifiedName:(NSString *)qName
attributes: (NSDictionary *)attributeDict{
if( [elementName isEqualToString:#"CheckDeviceTokenResult"])
{
}
else if( [elementName isEqualToString:#"a:UserID"])
{
if(!soapResults)
soapResults = [[NSMutableString alloc] init];
}
else if( [elementName isEqualToString:#"a:UserName"])
{
if(!soapResults)
soapResults = [[NSMutableString alloc] init];
}
}
-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{
if( [elementName isEqualToString:#"a:UserID"])
{
i = [soapResults intValue];
strUserID = soapResults;
soapResults = nil;
[dict setObject:strUserID forKey:#"id"];
}
else if( [elementName isEqualToString:#"a:UserName"])
{
strUserName = soapResults;
soapResults = nil;
[dict setObject:strUserName forKey:#"name"];
}
}
#end
When I debug my application and reach didEndElement, soapResult gives me nothing. On the contrary, when I use the same code in my controller class, I get the desired results, I wonder why.
You're not implementing parser:foundCharacters: I see that your allocating the string in start element but you would need to get the data out and set soapResults in foundCharacters. Where do you assign to soapResults? I don't see any code that ever assigns it which is why it's nil.
Also, didEndElement fires whenever the parser reaches the end of an element - not when it's done parsing. That would be parserDidEndDocument. So, it's possible that the parser hit the end of an element but still hasn't passed the two elements your interested in.

Failed to parse the XML 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.

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.