iphone web service application - iphone

Hi I am writing iphone application that communicates web service, So I have two textfield, program need to read the value of first textfield and post the web service then after the response from web service it need to write second text field. But in the second textfield it doesnt write any thing. it prints null on console. Why it becomes?
Thanks.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
nodeContent = [[NSMutableString alloc]init];
}
return self;
}
- (IBAction)login:(id)sender {
NSLog(#"PASSWORD text: %#",password.text);
if ([password.text length]==0) {
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"WebService" message:#"Supply Data in text field" delegate:nil cancelButtonTitle:nil otherButtonTitles:#"ok",nil];
[alert show];
[alert release];
}
else {
NSString *soapFormat = [NSString stringWithFormat:#"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
"<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/\">\n"
"<soap:Body>\n"
"<CelsiusToFahrenheit xmlns=\"http://tempuri.org/\">\n"
"<Celsius>%#</Celsius>\n"
"</CelsiusToFahrenheit>\n"
"</soap:Body>\n"
"</soap:Envelope>\n",password.text];
NSLog(#"The request format is %#",soapFormat);
NSURL *locationOfWebService = [NSURL URLWithString:#"http://www.w3schools.com/webservices/tempconvert.asmx"];
NSLog(#"web url = %#",locationOfWebService);
NSMutableURLRequest *theRequest = [[NSMutableURLRequest alloc]initWithURL:locationOfWebService];
NSString *msgLength = [NSString stringWithFormat:#"%d",[soapFormat length]];
[theRequest addValue:#"text/xml" forHTTPHeaderField:#"Content-Type"];
[theRequest addValue:#"http://tempuri.org/CelsiusToFahrenheit" forHTTPHeaderField:#"SOAPAction"];
[theRequest addValue:msgLength forHTTPHeaderField:#"Content-Length"];
[theRequest setHTTPMethod:#"POST"];
//the below encoding is used to send data over the net
[theRequest setHTTPBody:[soapFormat dataUsingEncoding:NSUTF8StringEncoding]];
NSURLConnection *connect = [[NSURLConnection alloc]initWithRequest:theRequest delegate:self];
if (connect) {
webData = [[NSMutableData alloc]init];
startActivityIndicator;
}
else {
NSLog(#"No Connection established");
}
// [self performSegueWithIdentifier:#"logindevam" sender:self];
}
}
- (IBAction)sendkeyboard:(id)sender {
[sender resignFirstResponder];
}
-(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);
xmlParser = [[NSXMLParser alloc]initWithData:webData];
[xmlParser setDelegate: self];
//[xmlParser setShouldResolveExternalEntities: YES];
[xmlParser parse];
//
[connection release];
//[webData release];
//[resultTable reloadData];
stopActivityIndicator;
}
//xml delegates
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict
{
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
[nodeContent appendString:[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]];
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
if ([elementName isEqualToString:#"CelsiusToFahrenheitResult"]) {
NSLog(#"nodeContent: %#",nodeContent); // it becomes null
finaldata = nodeContent;
NSLog(#"finaldata: %#",finaldata); // it becomes null
NSLog(#"username.text: %#",username.text); // it becomes null
username.text = finaldata;
}
username.text = finaldata;
}

Code::
-(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 = [theXML stringByReplacingOccurrencesOfString:#"<" withString:#"<"];
theXML = [theXML stringByReplacingOccurrencesOfString:#">" withString:#">"];
theXML = [theXML stringByReplacingOccurrencesOfString:#"&" withString:#"&"];
NSString *str, *result;
result = [[[NSString alloc] initWithFormat:#""] autorelease];
NSArray *array=[theXML componentsSeparatedByString:#"<CelsiusToFahrenheitResult>"];
for(int i=1;i<[array count];i++)
{
str=[array objectAtIndex:i];
NSRange ranfrom=[str rangeOfString:#"</CelsiusToFahrenheitResult>"];
result =[str substringToIndex:ranfrom.location];
}
NSLog(#"\n -> %#", result);
t2.text = result; // Your Second textfield
[connection release];
}
It'll definately work.
Thanks.

Related

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.

Web Services working on simulator, but not real device

I've just put my iOS app on my iPad, which is connected to my wireless network, and I cannot connect to web services. This was working in the simulator, however when I put it on the iPad, the connection times out. Is there something different needed when put on a real device?
Here is my code nevertheless:
-(BOOL)Webservice{
recordResults = FALSE;
user = nameInput.text;
pass = passwordInput.text;
NSString *soapMessage = [NSString stringWithFormat:
#"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
"<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/\">\n"
"<soap:Body>\n"
"<ValidateUser xmlns=\"http://tempuri.org/\">\n"
"<User>%#</User>\n"
"<Password>%#</Password>\n"
"</ValidateUser>\n"
"</soap:Body>\n"
"</soap:Envelope>\n", nameInput.text, passwordInput.text
];
NSLog(soapMessage);
NSURL *url = [NSURL URLWithString:#"http://192.168.51.3:60010/Webservice/IDLMobile.asmx?WSDL"];
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/ValidateUser" 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(#"theConnection is NULL");
}
[nameInput resignFirstResponder];
[passwordInput resignFirstResponder];
/* update function */
}
-(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];
if( xmlParser )
{
[xmlParser release];
}
xmlParser = [[NSXMLParser alloc] initWithData: webData];
[xmlParser setDelegate: self];
[xmlParser setShouldResolveExternalEntities: YES];
[xmlParser parse];
[connection release];
[webData release];
}
-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *) namespaceURI qualifiedName:(NSString *)qName
attributes: (NSDictionary *)attributeDict
{
if ([elementName isEqualToString:#"Message"])
{
//---displays the country---
NSLog(soapResults);
NSString *convertString = soapResults;
// check = 0;
check = [convertString intValue];
thyCheck = [convertString intValue];
NSLog(#"user is");
// NSLog(user);
if(check > 0){
[self someUpdateFunction];
NSString *string = [NSString stringWithFormat:#"%d", check];
NSLog(string);
NSLog(#"lolololol");
check = 0;
}else{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Problem!" message:#"Incorrect Username or Password"
delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:#"Yes", nil];
[alert show];
[alert release];
thyCheck = 0;
}
// gotoContent = checkConfirm;
}
if( [elementName isEqualToString:#"ValidateUserResponse"])
{
if(!soapResults)
{
soapResults = [[NSMutableString alloc] init];
NSLog(soapResults);
NSLog(#"above is soap validate user");
}
recordResults = TRUE;
}
}
-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
if( recordResults )
{
[soapResults appendString: string];
}
}
The other thing I could think of is that the iPhone MUST be connected to a 3G network? So it can't access web services through a connection to a router?
192.168.51.3 look like a private subnet of a network, could it be that you WiFi is on another subnet?

iPhone: Object is null in another view when set with values read from XML

I am reading an XML from and parsing the data in one viewController class. When I try to access the object in another view, it appears as null. The NSMutableArray is set with values in the earlier view. I need these values to set a picker view. Could you please let me know where am I going wrong? I have attached the code below: The value of testArray is null in the other view.
//Disclaimer.m file
NSString *soapMessage = [NSString stringWithFormat:
#"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
"<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/\">\n"
"<soap:Body>\n"
"<GetCommonCodeByCatg xmlns=\"http://longbeach.gov/PDPropertyReg/Services/\">\n"
"<catg>COLOR</catg>\n"
"</GetCommonCodeByCatg>\n"
"</soap:Body>\n"
"</soap:Envelope>\n"];
NSLog(#"Soap Message%#",soapMessage);
NSURL *url =[NSURL URLWithString:#"http://wwwbitdemo.longbeach.gov/PDPropertyReg/Services/CommonCode.asmx"];
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://longbeach.gov/PDPropertyReg/Services/GetCommonCodeByCatg" 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");
}
}
-(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(#"Connection Error");
[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(#"XML value %#",theXML);
[theXML release];
if (xmlParser) {
[xmlParser release];
}
xmlParser = [[NSXMLParser alloc]initWithData:webData];
[xmlParser setDelegate:self];
[xmlParser setShouldResolveExternalEntities:YES];
[xmlParser parse];
[connection release];
index =0;
}
-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{
if ([elementName isEqualToString:#"GetCommonCodeByCatgResult"]) {
self.testArray = [[NSMutableArray alloc]init];
}
else if ([elementName isEqualToString:#"SvcCommonCode"]) {
aCategory =[[Category alloc]init];
if ([elementName isEqualToString:#"CMCode"]) {
aCategory.CMCode = [attributeDict objectForKey:#"CMCode"];
}
NSLog(#"Reading the CMCode: %#",aCategory.CMCode);
}
NSLog(#"Processing element: %#", elementName);
}
-(void)parser: (NSXMLParser *)parser foundCharacters:(NSString *)string{
if (!currentElementValue)
currentElementValue =[[NSMutableString alloc]initWithString:string];
else
[currentElementValue appendString:string];
NSLog(#"Processing value:%#",currentElementValue);
}
-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{
if ([elementName isEqualToString:#"GetCommonCodeByCatgResult"]) {
return;
}
if ([elementName isEqualToString:#"SvcCommonCode"]) {
[self.testArray insertObject:aCategory atIndex:index];
index =index+1;
[aCategory release];
aCategory =nil;
}
else
[aCategory setValue:currentElementValue forKey:elementName];
[currentElementValue release];
currentElementValue = nil;
NSLog(#"Item count %i",[self.testArray count]);
}

validation username and password from server database in iphone

hi friends i am doing here validation for username and password from server database
by given url of server i think i am going wrong i don't think my code is right
please some help me how to validation from server database for username and password in iphone
-(IBAction)buttonClick:(id)sender
{
NSString* username = nameInput.text;
NSString* pass = passInput.text;
if([nameInput.text isEqualToString:#"" ]&& [passInput.text isEqualToString:#""])
{
//greeting.text = #"Input Your Value";
//[nameInput resignFirstResponder];
//[passInput resignFirstResponder];
//return;
}
NSString *post =
[[NSString alloc] initWithFormat:#"uname=%# & pwd=%#",username,pass];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSURL *url = [NSURL URLWithString:#"http://server:85/VirtualTerminal/RecordAttendance.aspx"];//#"https://www.google.com/accounts/ServiceLogin?service=reader&passive=1209600&continue=http://www.google.co.in/reader/?hl%3Den%26tab%3Dwy&followup=http://www.google.co.in/reader/?hl%3Den%26tab%3Dwy&hl=en"]; //#"http://www.chakrainteractive.com/mob/iphone/login/chckusr.php"];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
[theRequest setHTTPMethod:#"POST"];
[theRequest setValue:postLength forHTTPHeaderField:#"Content-Length"];
[theRequest setHTTPBody:postData];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if( theConnection )
{
webData = [[NSMutableData data] retain];
//test *t=[[test alloc]initWithNibName:#"test" bundle:nil];
//[self presentModalViewController:t animated:YES];
//[t release];
}
else
{
}
//}
[nameInput resignFirstResponder];
[passInput resignFirstResponder];
nameInput.text = nil;
passInput.text = nil;
k
[webData appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
[connection release];
[webData release];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSString *loginStatus = [[NSString alloc] initWithBytes: [webData mutableBytes] length:[webData length] encoding:NSUTF8StringEncoding];
NSLog(#"loginStatus");
greeting.text = loginStatus;
[loginStatus release];
[connection release];
[webData release];
}
Try setting with the following HTTPHeaderFields.
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"UTF-8" forHTTPHeaderField:#"charset"];
[request setValue:#"XMLHttpRequest" forHTTPHeaderField:#"X-Requested-With"];
I believe that the login call may be a "GET" method instead of "POST".
Once again confirm with the server URL that you make the call.
Thanks.
You can use this code:
-(IBAction)btnclick1:(id)sender
{
recordResult=FALSE;
greeting.text=#"Processing";
NSString *soapMessage=[NSString stringWithFormat:#" WEB SERVICE ",nameInput.text,passInput.text];
NSLog(#"%#",soapMessage);
NSURL *url=[NSURL URLWithString:#"http://SOME URL.asmx"];
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/webservicename" forHTTPHeaderField:#"SOAPAction"];
[theRequest addValue:msgLength forHTTPHeaderField:#"Content-Length"];
[theRequest setHTTPMethod:#"POST"];
[theRequest setHTTPBody:[soapMessage dataUsingEncoding:NSUTF8StringEncoding]];
NSURLConnection *theConnection=[[NSURLConnection alloc]initWithRequest:theRequest delegate:self];
[myActivity startAnimating];
if(theConnection)
{
webData=[[NSMutableData data]retain];
}
else
{
NSLog(#"theConnection is NULL");
}
[nameInpt resignFirstResponder];
[passinpt resignFirstResponder];
}
-----
-(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];
if(xmlParser)
{
[xmlParser release];
//xmlParser=nil;
}
xmlParser=[[NSXMLParser alloc]initWithData:webData];
[xmlParser setDelegate:self];
[xmlParser setShouldResolveExternalEntities:YES];
[xmlParser parse];
[myActivity stopAnimating];
[webData release];
//webData = nil;
[connection release];
}
-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *) namespaceURI qualifiedName:(NSString *)qName
{
if([myTxt1.text isEqualToString:#"webservresult"])
{
if(!soapResult)
{
soapResult=[[NSMutableString alloc]init];
}
recordResult=TRUE;
}
}
-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
if(recordResult)
{
[soapResult appendString:string];
}
}
-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
if([myTxt1.text isEqualToString:#"wsresult"])
{
recordResult=FALSE;
greeting.text=[NSString stringWithFormat:#"webservicename Result is:%#",soapResult];
[soapResult release];
soapResult=nil;
}
}
that's it.

Problem with XML parsing on iPhone

When I receive data from web service my NSMutableData is filled with following XML:
<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body><GetWeatherResponse xmlns="http://www.webserviceX.NET"><GetWeatherResult><?xml version="1.0" encoding="utf-16"?>
<CurrentWeather>
<Location>BERLIN MUNICIPAL AIRPORT, NH, United States (KBML) 44-35N 71-11W 345M</Location>
<Time>Oct 19, 2010 - 03:52 AM EDT / 2010.10.19 0752 UTC</Time>
<Wind> Calm:0</Wind>
<Visibility> 10 mile(s):0</Visibility>
<SkyConditions> clear</SkyConditions>
<Temperature> 23.0 F (-5.0 C)</Temperature>
<DewPoint> 21.0 F (-6.1 C)</DewPoint>
<RelativeHumidity> 91</RelativeHumidity>
<Pressure> 29.83 in. Hg (1010 hPa)</Pressure>
<Status>Success</Status>
</CurrentWeather></GetWeatherResult></GetWeatherResponse></soap:Body></soap:Envelope>
So when I search for "CurrentWeather" parser can't find it because of &qt, &lt etc. How to fix my NSMutableData to have normal values (<, > etc.)?
COMPLETE CODE
#import "DemoWebServiceConsumeViewController.h"
#implementation DemoWebServiceConsumeViewController
#synthesize cityName;
#synthesize activityIndicator;
#synthesize location;
- (IBAction) hideKeyboard{
[cityName resignFirstResponder];
}
- (IBAction) buttonClicked: (id)sender{
[cityName resignFirstResponder];
NSString *soapMsg =
[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>"
"<GetWeather xmlns=\"http://www.webserviceX.NET\">"
"<CityName>%#</CityName>"
"<CountryName>%#</CountryName>"
"</GetWeather>"
"</soap:Body>"
"</soap:Envelope>", cityName.text, #"united states"
];
NSLog(soapMsg);
NSURL *url = [NSURL URLWithString:
#"http://www.webservicex.com/globalweather.asmx"];
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
//---set the headers---
// here copy method name to be called SOAP Action read from WS description
NSString *msgLength = [NSString stringWithFormat:#"%d", [soapMsg length]];
[req addValue:#"text/xml; charset=utf-8"
forHTTPHeaderField:#"Content-Type"];
[req addValue:#"http://www.webserviceX.NET/GetWeather"
forHTTPHeaderField:#"SOAPAction"];
[req addValue:msgLength forHTTPHeaderField:#"Content-Length"];
//---set the HTTP method and body---
[req setHTTPMethod:#"POST"];
[req setHTTPBody: [soapMsg dataUsingEncoding:NSUTF8StringEncoding]];
[activityIndicator startAnimating];
conn = [[NSURLConnection alloc] initWithRequest:req delegate:self];
if (conn) {
webData = [[NSMutableData data] retain];
}
}
-(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 {
[webData release];
[connection release];
}
-(void) connectionDidFinishLoading:(NSURLConnection *) connection {
NSLog(#"DONE READING WEATHER WEB SERVICE. Received Bytes: %d", [webData length]);
NSString *theXML = [[NSString alloc]
initWithBytes: [webData mutableBytes]
length:[webData length]
encoding:NSUTF8StringEncoding];
//---shows the XML---
NSLog(theXML);
[theXML release];
[activityIndicator stopAnimating];
if (xmlParser)
{
[xmlParser release];
}
xmlParser = [[NSXMLParser alloc] initWithData: webData];
[xmlParser setDelegate:self];
[xmlParser setShouldResolveExternalEntities:YES];
[xmlParser parse];
[connection release];
[webData release];
}
//---when the start of an element is found---
-(void) parser:(NSXMLParser *) parser
didStartElement:(NSString *) elementName
namespaceURI:(NSString *) namespaceURI
qualifiedName:(NSString *) qName
attributes:(NSDictionary *) attributeDict {
NSLog(elementName);
if( [elementName isEqualToString:#"GetWeatherResult"])
{
if (!soapResults)
{
soapResults = [[NSMutableString alloc] init];
}
elementFound = YES;
}
else if([elementName isEqualToString:#"Location"])
{
elementFound = YES;
}
}
-(void)parser:(NSXMLParser *) parser foundCharacters:(NSString *)string
{
if (elementFound)
{
[soapResults appendString: string];
}
}
-(void)parser:(NSXMLParser *)parser
didEndElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI
qualifiedName:(NSString *)qName
{
if ([elementName isEqualToString:#"GetWeatherResult"])
{
NSLog(soapResults);
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:#"Current Temperature!"
message:soapResults
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
[alert release];
[soapResults setString:#""];
elementFound = FALSE;
}
}
#end
I've edited your question so it shows what I think is what you meant to paste. It looks like the web service is encapsulating a whole XML file as a string inside another XML tag. So what you need to do is get the entire content of the <GetWeatherResult> XML tag as a single string. I think NSXMLParser will automatically substitute the correct characters in place of > etc.
Having got that string, you need to pass it into another NSXMLParser to parse the content of it.