Web service request in Objective C - iphone

I am new in objective C. I have done app in j2me and android using below code. I m trying same to consume web service through objective C but not getting success. It will be great if anyone guide me.
Thanks.
public static String RetriveData(String myStr)
{
String result1 = "-1";
Object ob1 = new Object();
ob1 =MyStr;
SoapObject rpc = new SoapObject("http://abcd.com/", "MyMethod");
rpc.addProperty("Mystr", ob1.toString());
try
{
Object strdata = new HttpTransport("http://11.22.33.44/myService.asmx", "http://abcd.com/" + "MyMethod").call(rpc);
result1 = strdata.toString().trim();
}
catch (Exception ex)
{
System.out.println("In catch block :" +ex);
}
return result1;
}
I am trying same through objective C as below but getting error.
NSURL *url = [NSURL URLWithString:#"http://11.22.33.44/MyService.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://abcd.com/MyMethod" forHTTPHeaderField:#"SOAPAction"];
//[theRequest addValue: msgLength forHTTPHeaderField:#"Content-Length"];
[theRequest addValue:#"MyStr" forHTTPHeaderField:#"MyStr"];
[theRequest setHTTPMethod:#"POST"];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if( theConnection )
{
webData = [[NSMutableData data] retain];
}
else
{
NSLog(#"theConnection is NULL");
}
[nameInput resignFirstResponder];
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[webData setLength: 0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[webData appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(#"ERROR with theConenction");
[connection release];
[webData release];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(#"DONE. Received Bytes: %d", [webData length]);
NSString *theXML = [[NSString alloc] initWithBytes: [webData mutableBytes] length:
[webData length] encoding:NSUTF8StringEncoding];
NSLog(theXML);
[theXML release];
if( xmlParser )
{
[xmlParser release];
}
xmlParser = [[NSXMLParser alloc] initWithData: webData];
[xmlParser setDelegate: self];
[xmlParser setShouldResolveExternalEntities: YES];
[xmlParser parse];
[connection release];
[webData release];
}

My personal recommendation is to use ASIHttpRequest. I consume web services (both .NET and PHP) with it and it seems much easier and straightforward to use in most cases.
Just include the ASIHttpRequest classes and the MBProgressHUD (If you want to use it)
Here is what I use to do it:
MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
hud.labelText = #"Connecting to Server";
// Start request
NSURL *url = [NSURL URLWithString:#"http://mydomain/MyWebService.asmx/MyMethod"];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setValidatesSecureCertificate:NO];
// Now setup the Request
[request setPostValue:#"MyValue1" forKey:#"WebServiceArg1"];
[request setPostValue:#"MyValue2" forKey:#"WebServiceArg2"];
[request setDelegate:self];
[request startAsynchronous];
Now use the delegate methods to check and consume the response from the web service:
#pragma mark - ASIHttpRequest Delegate Methods
- (void)requestFinished:(ASIHTTPRequest *)request
{
[MBProgressHUD hideHUDForView:self.view animated:YES];
if (request.responseStatusCode == 200) {
NSString *responseString = [request responseString];
// Do something with this, create an array or dictionary depending on how the return data is structured (this assumes you are using a JSON formatted return string btw
}
else {
// Standard UIAlert Syntax
UIAlertView *myAlert = [[UIAlertView alloc]
initWithTitle:#"Connection Error"
message:#"My Message"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil, nil];
[myAlert show];
}
} else {
NSLog(#"Error finishing request");
}
}
- (void)requestFailed:(ASIHTTPRequest *)request
{
[MBProgressHUD hideHUDForView:self.view animated:YES];
// Standard UIAlert Syntax
UIAlertView *myAlert = [[UIAlertView alloc]
initWithTitle:#"Connection Error"
message:#"Unable to establish connection"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil, nil];
[myAlert show];
NSError *error = [request error];
NSLog(#"%#",error.localizedDescription);
}
There are many ways to do it but this is what I would use.

Related

POST username and password in JSON

I have a web service I am working with a url such as
//myurl/index.jsp?user_name=bob&user_pwd=new
as you can see the username has been set as "bob" and password "new". The site give this json file when entered,
[{"success":"1"}]
How do you implemented it on xcode, where when a user enters "bob" as username and "new" as password it should lead to the next controller. How do can I achieve that ?
I followed this tutorial though it's not quite the same, how do you do this. Thanks.
Use a navigation controller and set you view controller as the rootViewController. Then after the user has entered the credentials push the new view controller onto the navigation stack.
Get the value of success from json response. If it is equal to 1 then push to next controller else do nothing.
In Following code you can pass data by either GET or POST method … use any one (As You Wish)
-(void) sendRequest
{
//////////////////////////// GET METHOD /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
NSString *strURL=[NSString stringWithFormat:#"http://myurl/index.jsp?user_name=bob&user_pwd=new"];
self.request=[NSURLRequest requestWithURL:[NSURL URLWithString:strURL]];
self.nsCon=[[NSURLConnection alloc] initWithRequest:request delegate:self];
//////////////////////////// POST METHOD /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
NSString *postString = [NSString stringWithFormat:#"&user_name=bob&user_pwd=new"];
NSString *url = [NSString stringWithFormat:#"http://myurl/index.jsp/"];
self.request =[NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
[self.request setHTTPMethod:#"POST"];
[self.request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
if(self.nsCon)
{
self.receivedData=[[NSMutableData alloc] init];
}
else
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(#"Error",#"") message:NSLocalizedString(#"Not Connected !!",#"") delegate:nil cancelButtonTitle:NSLocalizedString(#"OK",#"") otherButtonTitles:nil];
[alert show];
[alert release];
}
}
#pragma mark -
#pragma mark - Connection Delegate Methods
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[self.responseData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[self.responseData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
[GeneralClass stopHUD];
NSLog(#"Connection failed.");
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(#"Error",#"") message:NSLocalizedString(#"Connection failed!",#"") delegate:nil cancelButtonTitle:NSLocalizedString(#"OK",#"") otherButtonTitles:nil];
[alert show]; alert = nil;
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSString *responseString = [[NSString alloc] initWithData:self.responseData encoding:NSUTF8StringEncoding];
NSMutableDictionary *receivedData = [responseString JSONValue];
if([[receivedData objectForKey:#"success"] isEqualToString:#"1"])
{
MainDetailViewController *mdController = [[MainDetailViewController alloc] init];
[self.navigationController pushViewController:mdController animated:YES];
}
else
{
NSLog(#"%#",receivedData);
}
}
Post login data
NSString *soapMsg = [NSString stringWithFormat:#"&data={\"LoginUser\":[{\"UserName\":\"%#\",\"Password\":\"%#\"}]}",firstname.text, password.text];
NSHTTPURLResponse *response;
NSData *myRequestData = [ NSData dataWithBytes: [ soapMsg UTF8String ] length: [ soapMsg length ] ];
NSString *postLength = [NSString stringWithFormat:#"%d", [myRequestData length]];
NSMutableURLRequest *request = [ [ NSMutableURLRequest alloc ] initWithURL: [ NSURL URLWithString:#"http://myurl/index.jsp"]];
[request setHTTPMethod: #"POST" ];
[request setHTTPBody: myRequestData ];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody: myRequestData];
NSURLConnection *myConnection=[[NSURLConnection alloc] initWithRequest:request delegate:self];
Receive and vaild json data
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSString *responseString = [[NSString alloc] initWithData:WebXmlData encoding:NSUTF8StringEncoding];
NSDictionary *results = [responseString JSONValue];
BOOL success = [[results objectForKey:#"success"] boolValue];
if (success) {
ViewController *viewController =[[ViewController alloc]initWithNibName:#"ViewController" bundle:nil];
[self.navigationController pushViewController:viewController animated:YES];
}
}
Not quite the answer you are looking for but this is more a recommendation for what should you use.
I use github link for Network related activities.
They have nice documentation and very easy to use (uses blocks)
NSDictionary *paramsDictionary = [NSDictionary dictionaryWithObjectsAndKeys:#"user",#"client_id",#"password",#"new", nil];
[[YourAFHttpClientExtenstion sharedInstance] postPath:LOGIN_PATH parameters:paramsDictionary success:^(AFHTTPRequestOperation *operation, id responseObject) {
//handle success
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
// handle error.
}];
YourAFHttpClientExtenstion is extending AFHttpClient and adds a convening method of shared instance and implements initWithBaseUr:

How to check whether it is ended xml parsing

After processing the XML data (read xml data and insert sqlite reading data....etc), I'd like to move to the next view.
How can I check whether it is finished parsing the XML?
I attach my code. Where can I check if parsing has finished?
-(IBAction)clickServerSync:(id)sender
{
if ([util checkNetwork]) {
[self LoadXml:#"LANG"];
[self LoadXml:#"CATEGORY"];
[self LoadXml:#"LIST"];
[self LoadXml:#"FILE"];
}
}
-(void)LoadXml:(NSString*)P_VAL
{
[indicator setHidden:NO];
NSString *smsURL = [NSString stringWithFormat:#"%#%#.asp", XML_URL, P_VAL];
NSString *sendAuthInfo = [NSString stringWithFormat:#"xx=%d" , 0 ];
NSString *val = [sendAuthInfo stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:smsURL]]autorelease];
[request setURL:[NSURL URLWithString:smsURL]];
[request setHTTPMethod:#"POST"];
[request setHTTPBody: [val dataUsingEncoding:NSUTF8StringEncoding]];
[self startAsyncLoad:request tag:P_VAL];
}
- (void)startAsyncLoad:(NSMutableURLRequest*)request tag:(NSString*)tag {
CustomURLConnection *connection = [[CustomURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES tag:tag];
if (connection) {
[receivedData setObject:[[NSMutableData data] retain] forKey:connection.tag];
}
}
- (NSMutableData*)dataForConnection:(CustomURLConnection*)connection {
NSMutableData *data = [receivedData objectForKey:connection.tag];
return data;
}
-(void)check_xmlParserEnd
{
[indicator setHidden:YES];
}
- (void)connection:(CustomURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
NSMutableData *dataForConnection = [self dataForConnection:(CustomURLConnection*)connection];
[dataForConnection setLength:0];
}
- (void)connection:(CustomURLConnection *)connection didReceiveData:(NSData *)data {
NSMutableData *dataForConnection = [self dataForConnection:(CustomURLConnection*)connection];
[dataForConnection appendData:data];
}
-(void)connectionDidFinishLoading:(CustomURLConnection*)connection
{
NSMutableData *dataForConnection = [self dataForConnection:(CustomURLConnection*)connection];
[connection release];
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
NSXMLParser *xmlParser = [[[NSXMLParser alloc] initWithData:dataForConnection] autorelease];
XMLParser *parser = [[XMLParser alloc] initXMLParser];
[xmlParser setDelegate:(id)parser];
parser.viewDelegate = (id)self;
[xmlParser parse ];
}
NSXMLParser is a synchronous parser. As soon as [xmlParser parse] returns , the parsing is done.
Since you use NSXMLParser and you set delegate as self, your class should implement NSXMLParserDelegate methods and the one "– parserDidEndDocument:" is called when all is finished.

Better approach to performing a series of SOAP requests in Objective-C

I use the following hack-job code to perform a series of SOAP requests that download data from a server for use in the application:
This code is called when the 'update' button is pressed:
- (IBAction) update {
UIAlertView *errorView;
if([[Reachability reachabilityForInternetConnection] currentReachabilityStatus] == NotReachable) {
errorView = [[UIAlertView alloc]
initWithTitle: #"Network Error"
message: #"No Network connection availible!"
delegate: self
cancelButtonTitle: #"OK" otherButtonTitles: nil];
[errorView show];
}
else
{
[appDelegate.categories removeAllObjects];
[appDelegate.currencies removeAllObjects];
[appDelegate.projects removeAllObjects];
HUD = [MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
HUD.labelText = #"Downloading..";
[self requestCategories];
}
}
Below is a typical request, I use approximately 6 of them.
// SOAP requests
- (void) requestCategories {
// Indeterminate mode
categories = [[NSMutableArray alloc] init];
xmlBlock = CATEGORY;
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> <Categories xmlns=\"http://tempuri.org/\"> <UID>string</UID> <Username>string</Username> <Password>string</Password> </Categories> </soap:Body> </soap:Envelope>"
];
//---print it to the Debugger Console for verification---
NSLog(#"%#", soapMsg);
NSURL *url = [NSURL URLWithString:
#"http://www.$$%$%^^^%$$££.co.uk/%$^£^£^$&£.asmx"];
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
//---set the headers---
NSString *msgLength = [NSString stringWithFormat:#"%d",
[soapMsg length]];
[req addValue:#"text/xml; charset=utf-8"
forHTTPHeaderField:#"Content-Type"];
[req addValue:#"http://tempuri.org/Categories"
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];
}
}
Below are my delegate methods for NSURLConnection (and a parsing method):
-(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 {
}
-(void) connectionDidFinishLoading:(NSURLConnection *) connection {
NSLog(#"DONE. Received Bytes: %d", [webData length]);
NSString *theXML = [[NSString alloc]
initWithBytes: [webData mutableBytes]
length:[webData length]
encoding:NSUTF8StringEncoding];
//---shows the XML---
NSLog(#"%#", theXML);
if (xmlBlock == CATEGORY){
[self parseXML:webData];
[self requestCurrencies];
}
else if (xmlBlock == CURRENCY){
[self parseXML:webData];
[self requestNominals];
}
else if (xmlBlock == NOMINAL){
[self parseXML:webData];
[self requestProjects];
}
else if (xmlBlock == PROJECT){
[self parseXML:webData];
[self requestRegister];
}
else {
[self parseXML:webData];
HUD.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"37x-Checkmark.png"]];
HUD.labelText = #"Done!";
HUD.mode = MBProgressHUDModeCustomView;
[HUD hide:YES afterDelay:2];
}
}
- (void) parseXML: (NSMutableData *)localWebData {
xmlParser = [[NSXMLParser alloc] initWithData: localWebData];
[xmlParser setDelegate: self];
[xmlParser setShouldResolveExternalEntities:YES];
[xmlParser parse];
}
I don't think you need to see my xml parsing delegate methods (if you do let me know). My question is, is there a better way to implement this functionality in my app? As in perform the requests one after another while displaying some kind of progress indicator to the user?
Thanks,
Jack
use NSOperation queue, that is make your class a subclass of NSOperation in which you are sending the request to service, and rename of your method to main. then make the property of this class in parent class and add all the request in operation queue. And for the finishing, use keyobserver for your that property of nsopertion subclass

how to update data in server database in same field in iphone

I am updating my data but it not updating why it happen
i want if any register user want to change data old to new then i give a update page where the user change there data but except username i try lot byt it's not updata data to server databasetable my cod is proper or wrong
-(void)sendRequest
{
NSString *post = [NSString stringWithFormat:#"firstname=%#&lastname=%#&Username=%#&Password=%#&Email=%#",txtfirstName.text,txtlast.text,txtUserName.text,txtPassword.text,txtEmail.text];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSLog(#"%#",postLength);
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:#"http://192.168.0.1:96/JourneyMapperAPI?RequestType=Register&Command=SET"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (theConnection) {
webData = [[NSMutableData data] retain];
NSLog(#"%#",webData);
}
else
{
}
}
-(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
{
[connection release];
[webData release];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSString *loginStatus = [[NSString alloc] initWithBytes: [webData mutableBytes] length:[webData length] encoding:NSUTF8StringEncoding];
NSLog(#"%#",loginStatus);
}
you need to start the connection:
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (theConnection) {
webData = [[NSMutableData data] retain];
NSLog(#"%#",webData);
[theConnection start];
}
else
{
}

Http Post Request

How to make Http Post Request using JSON. I tried every option which is available on Internet.But could not get the Data. So please post entire code to make a request.
You can use below code:
-(void)performRequest{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:#"url"]];
NSString *msgLength = [NSString stringWithFormat:#"%d", [jsonMessage length]];
[request addValue: #"text/xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[request addValue: jsonAction forHTTPHeaderField:#"JSONAction"];
[request addValue: msgLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPMethod:#"POST"];
[request setHTTPBody: [jsonMessage 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];
}
}
Here's a basic example of NSURLConnection POST-ing JSON to an URL.
- (void)performRequest {
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:#"http://someplace.com/"]];
[request setValue:#"Some Value" forHTTPHeaderField:#"Some-Header"];
[request setHTTPBody:#"{\"add_json\":\"here\"}"];
[request setHTTPMethod:#"POST"];
[NSURLConnection connectionWithRequest:[request autorelease] delegate:self];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
// Fail..
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
// Request performed.
}