Getting Data From .net Web Service on iOS - iphone

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

Related

ios web service login returns empty xml response

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

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.

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.