How to add NSXML parser in class? - iphone

I want to add NSXML parser in to my Objective-C class and parse XML file
in .h file
NSMutableData *myWebData; NSXMLParser *myXMLParser; NSString *tempStr;
in .m life
(void)ViewDidLoad
{
NSString *soapMsg=#"<?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"
"<GetCountryList xmlns=\"http://tempuri.org/\" />"
"</soap:Body>"
"</soap:Envelope>";
NSURL *myurl=[NSURL URLWithString:#"http://iphone.dotnetdemosite.com/Health4Life/Health4Life_Service.asmx?op=GetCountryList"];
NSMutableURLRequest *connectionReq=[NSMutableURLRequest requestWithURL:myurl];
[connectionReq addValue:#"text/xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[connectionReq addValue:#"http://tempuri.org/GetCountryList" forHTTPHeaderField:#"SOAPAction"];
[connectionReq setHTTPBody: [soapMsg dataUsingEncoding:NSUTF8StringEncoding]];
[connectionReq addValue:[NSString stringWithFormat:#"%i",[soapMsg length]] forHTTPHeaderField:#"Content-Length"];
[connectionReq setHTTPMethod:#"POST"];
NSURLConnection *myConnection=[[NSURLConnection alloc] initWithRequest:connectionReq delegate:self];
if (myConnection) {
myWebData=[[NSMutableData alloc]initWithLength:0];
}
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(#"connection error");
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[myWebData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[myWebData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSString *str=[[NSString alloc] initWithBytes:[myWebData bytes] length:[myWebData length] encoding:NSStringEncodingConversionAllowLossy];
NSLog(#"%#",str);
[str release];
if(myXMLParser!=nil && [myXMLParser retainCount]>0)
{
myXMLParser.delegate=nil;
[myXMLParser release];
myXMLParser=nil;
}
myXMLParser=[[NSXMLParser alloc] initWithData:myWebData];
myXMLParser.delegate=self;
[myXMLParser parse];
[connection release];
[myWebData release];
}
-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict
{
/////////////// logic here
}
-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
if(tempStr!=nil && [tempStr retainCount]>0)
{
[tempStr release]; tempStr=nil;
}
tempStr=[[NSString alloc] initWithString:string];
}
-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
///////////////logic here
}
- (void)parserDidEndDocument:(NSXMLParser *)parser
{
//NSLog(#"%#",[countryArray description]);
// NSLog(#"%#",[stateArray description]);
// NSLog(#"%#",[cityArray description]);
//NSLog(#"%#",[tempstate description]);
///////////////////// print array if you want in this you will get all data in array ,
//[(UITableView *)self.view reloadData];
}

hi friend i think you need to learn about nsxmlparser delegate
there are three delegate methods
didstartelement
didendelement
foundcharacter
and one suggestion to all if you not answering please do not downvote someone atleast he/she try for this you can add comment if they are wrong

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.

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!!

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

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.

Webservice n sqlite

I have web services and I want to save that data in SQLite in iPhone and also want to retrieve that data. Web services include 14 parameters, also includes image URL as well. Web service is SOAP in .NET.
Please help me and provide me with the complete code how to do that.
Webservices may be in Java, PHP, .NET and etc... But you have to use same procedure to make a request.
Here I have given sample code to make a request and get the response from webservices.
-(void)performRequest{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:#"url"]];
NSString *msgLength = [NSString stringWithFormat:#"%d", [soapMessage length]];
[request addValue: #"text/xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[request addValue: soapAction forHTTPHeaderField:#"SOAPAction"];
[request addValue: msgLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPMethod:#"POST"];
[request setHTTPBody: [soapMessage dataUsingEncoding:NSUTF8StringEncoding]];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if( theConnection )
{
webData = [[NSMutableData data] retain];
}
else
{
NSLog(#"theConnection is NULL");
}
[pool release];
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
[webData setLength: 0];
self.resultArray = [[NSMutableArray alloc] init];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
[webData appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
NSLog(#"ERROR with theConenction");
NSDictionary *errorDic = [NSDictionary dictionaryWithObject:error forKey:#"error"];
[self.resultArray addObject:errorDic];
[connection release];
[webData setLength:0];
}
-(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([webData length] > 0){
parser = [[NSXMLParser alloc] initWithData:webData];
[parser setDelegate:self];
[parser parse];
}
}
In this example, "webData"(NSData) having the response data. The request should be in XML format and also the response data will be in XML format. Using NSXMLParser you can parse the data.
There is some delegate methods. You have to use below specified methods;
1. - (void)parserDidStartDocument:(NSXMLParser *)parser
2. - (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict
3. - (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
4. - (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
5. - (void)parserDidEndDocument:(NSXMLParser *)parser
6. - (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError
in 2nd delegate method, you will get the element name (xml tag name).
in 3rd delegate method, you will get the value for the element name.
I hope, it will help you.