How to Receive data from the Server in iPhone

  • Home >>
  • iOS
  • >> How to Receive data from the Server in iPhone

In this application we will see how to receive data from the server. This is the simple login application and when you login in the screen it will display the message, whatever we set in the server page. So let see how it will be worked.

Step 1: Create a View base application using template. Give the application name “SendReceiveData”.

Step 2: Xcode automatically creates the directory structure and adds essential frameworks to it. You can explore the directory structure to check out the content of the directory.

Step 3: Xpand classes and notice Interface Builder created the SendReceiveDataViewController class for you. Expand Resources and notice the template generated a separate nib, SendReceiveDatayViewController.xib, for the “SendReceiveData”.

Step 4: In the SendReceiveDataViewController.h file, we have added UITextField, UILabel, and one buttonClick method. So make the following changes in the file.

#import <uikit/UIKit.h>

@interface SendReceiveDataViewController :
UIViewController<uitextFieldDelegate> {

	IBOutlet UITextField *nameInput;
	IBOutlet UITextField *passInput;
	IBOutlet UILabel *greeting;
	NSMutableData *webData;

}

@property(nonatomic, retain) IBOutlet UITextField *nameInput;
@property(nonatomic, retain) IBOutlet UITextField *passInput;
@property(nonatomic, retain) IBOutlet UILabel *greeting;
@property(nonatomic, retain) NSMutableData *webData;

-(IBAction)buttonClick: (id) sender;

Step 5: Double click the SendReceiveDataViewController.xib file and open it to the Interface Builder. Drag three labels, one Round Rect Button and two TextField from the library and place it to the view window(See the figure below). Connect File’s Owner icon to the view icon and select view and drag File’s Owner icon to the “Input Your Values” and select greeting . Next drag File’s Owner icon to the first text field and select nameInput,do the same thing for the next text field and select passInput. Select the login button and bring up Connection Inspector and drag TouchUpInside to the File’s Owner icon and select buttonClick: action. Now save the SendReceiveDataViewController.xib file, close it and go back to the Xcode.

Step 6: Open the SendReceiveDataViewController.m file and make the following changes in the file:

-(IBAction)buttonClick:(id)sender
{

	NSString* username = nameInput.text;
	NSString* pass = passInput.text;

	if([nameInput.text isEqualToString:@"" ]|| [passInput.text isEqualToString:@""])
	{

		greeting.text = @"Input Your Value";
		[nameInput resignFirstResponder];
		[passInput resignFirstResponder];
		return;
	}

	NSString *post =
	[[NSString alloc] initWithFormat:@"uname=%@&pwd=%@",username,pass];

	NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];

	NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];

	NSURL *url = [NSURL URLWithString:@"http://www.chakrainteractive.com/mob/iphone/login/chckusr.php"];
	NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
	[theRequest setHTTPMethod:@"POST"];
	[theRequest setValue:postLength forHTTPHeaderField:@"Content-Length"];
	[theRequest setHTTPBody:postData];


	NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];

	if( theConnection )
	{
		webData = [[NSMutableData data] retain];
	}
	else
	{

	}

	[nameInput resignFirstResponder];
	[passInput resignFirstResponder];
	nameInput.text = nil;
	passInput.text = nil;

}

-(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);
	greeting.text = loginStatus;
	[loginStatus release];



	[connection release];
	[webData release];
}

Step 7: Now compile and run the application in the Simulator.

You can Download SourceCode from here SendReceiveData-1

About the Author

Leave a Reply 17 comments

Pascal - June 15, 2010 Reply

Hello,

what would be the code for a “cancel” button? How can I close the pending connection before it is completed? Thanks.

Pascal

Pascal - June 15, 2010 Reply

Hello,

what would be the code for a "cancel" button? How can I close the pending connection before it is completed? Thanks.

Pascal

mapega - June 19, 2010 Reply

Can you tell me a correct login and password for test, please?

Sushant - June 19, 2010 Reply

In our application, we are not set username and password, when user input username and password and click it then invalid message display in the screen that message comes from the server.

mapega - June 19, 2010 Reply

Thanks for your answer. Is possible to download chckusr.php. It should be great to understand completly. Thanks in advance.

If you can’t by this way, may be you can send me the file by e-mail…

mapega - June 19, 2010 Reply

Ok, I create my own php and it works perfect. Thanks for your post, It help me a lot. Thanks :)

davidv - June 22, 2010 Reply

What is the function that PHP uses to return the message back to the app…
I am using ColdFusion.

Tony - July 6, 2010 Reply

all you have to do on the server side is read the posted vars uname and pwd and then echo something. I did a quick if statement like this…

This is my first app, so I don’t know how to send back specific data in vars like you would in AS3 or something like that… this is just reading the string on the page. This looks like a basic idea of how to get information to and from a web server. From there you can use the web server to manipulate your inputs and retrieve data. The possibilities are endless…. I love this stuff!

Tony - July 6, 2010 Reply

all you have to do on the server side is read the posted vars uname and pwd and then echo something. I did a quick if statement like this…

<php?
$user = $_POST[‘uname’];

if ($user == ‘tony’)
{
echo "You are the coolest guy I know";
}else{
echo "You suck"
}
?>

This is my first app, so I don’t know how to send back specific data in vars like you would in AS3 or something like that… this is just reading the string on the page. This looks like a basic idea of how to get information to and from a web server. From there you can use the web server to manipulate your inputs and retrieve data. The possibilities are endless…. I love this stuff!

Abi - July 24, 2010 Reply

Thanks for this apps

arpan - August 4, 2010 Reply

will u plz send the chckusr.php source codes…

Dipak Patil - January 6, 2011 Reply

please,
give one example on socket programming in iphone,
how can we send message from client(iphone) to server.
give one demo app. please.

casper - January 27, 2011 Reply

if i want it for GET .. what should i do? ..

i am using it to login on website .. but the thing is that i m getting an error msg which is invalid username and password .. :S

Dmitri - June 20, 2012 Reply

Thank you so so much for this tutorial! 😀

RickyRan - June 27, 2012 Reply

All I am getting is (null) as the output, is the server still up?

Leave a Reply: