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, < 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.
Related
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
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.
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.
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?
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!!