Webservices In Apple Iphone connection - iphone

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.

Related

Getting Data From .net Web Service on iOS

I have one .Net web service and I use it for mobile apps. I used it on windows phone and android apps but I didn't get data from it on iOS yet. For example, there is one method in my web service and it takes one parameter. How can I get data from returning value ? I found one example on internet and I edited it but I can't get data. All of code is here. In this case I need a sample code. Thanks for attention.
web service's information:
namespace : http://tempuri.org
url : http://www.example.com/webservice1.asmx
method name : FirmaGetir
parameter name: firID (string)
Web service request:
POST /webservice1.asmx HTTP/1.1
Host: example.com
Content-Type: application/soap+xml; charset=utf-8
Content-Length: length
<?xml version="1.0" encoding="utf-8"?>
<soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">
<soap12:Body>
<FirmaGetir xmlns="http://tempuri.org/">
<firID>string</firID>
</FirmaGetir>
</soap12:Body>
</soap12:Envelope>
Returning data:
HTTP/1.1 200 OK
Content-Type: application/soap+xml; charset=utf-8
Content-Length: length
<?xml version="1.0" encoding="utf-8"?>
<soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">
<soap12:Body>
<FirmaGetirResponse xmlns="http://tempuri.org/">
<FirmaGetirResult>
<Firma>
<firma_adi>string</firma_adi>
<adres>string</adres>
<telefon>string</telefon>
<id>string</id>
<sektor>string</sektor>
<alt_sektor>string</alt_sektor>
<alt_sektor_adi>string</alt_sektor_adi>
<servis>string</servis>
<map>string</map>
<slogan>string</slogan>
<sayfaGosterimi>int</sayfaGosterimi>
<gpsilce>string</gpsilce>
<gpssemt>string</gpssemt>
<gpspk>string</gpspk>
<duyuru>
<baslik>string</baslik>
<icerik>string</icerik>
<link>string</link>
<image>string</image>
</duyuru>
<firma_link>
<tam_adi>string</tam_adi>
<kisa_adi>string</kisa_adi>
<firma_link>string</firma_link>
</firma_link>
</Firma>
</FirmaGetirResult>
</FirmaGetirResponse>
</soap12:Body>
</soap12:Envelope>
SOAPExampleViewController.h
#import <UIKit/UIKit.h>
#interface SOAPExampleViewController : UIViewController
{
NSXMLParser *xmlParser;
NSMutableData *webData;
NSMutableString *soapResults;
BOOL recordResults;
}
#property(nonatomic, retain) NSMutableData *webData;
#property(nonatomic, retain) NSXMLParser *xmlParser;
#property(nonatomic, retain) NSMutableString *soapResults;
-(IBAction)buttonClick:(id)sender;
#end
SOAPExampleViewController.m
#import "SOAPExampleViewController.h"
#implementation SOAPExampleViewController
#synthesize xmlParser, webData, soapResults;
-(IBAction)buttonClick:(id)sender
{
NSString *firid = [NSString stringWithFormat:#"800"];
recordResults = NO;
NSString *soapMessage = [NSString stringWithFormat:
#"POST /webservice1.asmx HTTP/1.1\n"
"Host: example.com\n"
"Content-Type: application/soap+xml; charset=utf-8\n"
"Content-Length: length\n"
"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
"<soap12:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap12=\"http://www.w3.org/2003/05/soap-envelope\">\n"
"<soap12:Body>\n"
"<FirmaGetir xmlns=\"http://tempuri.org/\">\n"
"<firID>%#</firID>\n"
"</FirmaGetir>\n"
"</soap12:Body>\n"
"</soap12:Envelope>\n",firid];
NSLog(#"%#", soapMessage);
NSURL *url = [NSURL URLWithString:#"http://www.example.com/webservice1.asmx?op=FirmaGetir"];
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/FirmaGetir" 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");
}
}
-(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(#"webdata: %#", data);
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError*)error
{
NSLog(#"error with the connection");
[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 %#",theXML);
[theXML release];
NSString *responseString = [[NSString alloc] initWithData:webData encoding:NSUTF8StringEncoding];
NSLog(#"Respose Data :%#",responseString) ;
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 *)qualifiedName attributes:(NSDictionary *)attributeDict
{
if([elementName isEqualToString:#"firma_adi"] || [elementName isEqualToString:#"Firma"] || [elementName isEqualToString:#"adres"] ) //I'm trying
{
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:#"firma_adi"] || [elementName isEqualToString:#"Firma"] || [elementName isEqualToString:#"adres"] ) // I'm trying
{
recordResults = NO;
NSLog(#"%#", soapResults);
[soapResults release];
soapResults = nil;
}
}
Replace the line below
NSURL *url = [NSURL URLWithString:#"http://www.example.com/webservice1.asmx"];
by this one.
NSURL *url = [NSURL URLWithString:#"http://www.example.com/webservice1.asmx/ServisKontrol"];
It will help.
or just try a great free tool that generates you all the classes and proxy u need.
wsdl2code.com
I was trying solve this issue about one week. I don't search anymore about it. The best way for consuming web service is using WCF services with JSON. I found an excellent example about of it. Please follow this tutorial http://www.codeproject.com/Articles/405189/How-to-access-SQL-database-from-an-iPhone-app-Via
Change http://tempuri.org/FirmaGetir with http://tempuri.org/ServisKontrol in SOAPAction.
Also you can refer this link for more information. iPhone interaction with ASP.NET WebService

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.

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.

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

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.