Send Data to server in iOS using POST OR GET – A Simple Example

By | February 14, 2016

First Make sure you have this kind of layout and you have linked all the views to their respective variables.

For server side I am using XAMPP for Localhost for now and My php file will be residing in Applications ▸ XAMPP ▸ xamppfiles ▸ htdocs

You can download “XAMPP For Mac” from this link.

When copying this code, make changes according to your server.

 

iOS Server Connection using POST and GET

 

So I will go directly to the code.

ViewController.h


#import <UIKit/UIKit.h>

@interface ViewController : UIViewController<NSURLConnectionDelegate>
{
    IBOutlet UITextField *username, *passsword;
    IBOutlet UILabel *serverResponse;
}

@end

ViewController.m


#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController{
    
    NSMutableData *mutableData;
    
    #define URL            @"http://localhost/test.php"  // change this URL
    #define NO_CONNECTION  @"No Connection"
    #define NO_VALUES      @"Please enter parameter values"
   
}

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
}

-(IBAction)sendDataUsingPost:(id)sender{
    
    [self sendDataToServer :@"POST"];
   
}

-(IBAction)sendDataUsingGet:(id)sender{
    
    [self sendDataToServer : @"GET"];
}

-(void) sendDataToServer : (NSString *) method{
    
    NSString *usrname  = username.text;
    NSString *pass = passsword.text;
    
    if(usrname.length > 0 && pass.length > 0){
        
        serverResponse.text = @"Getting response from server...";
        
        NSURL *url = nil;
        NSMutableURLRequest *request = nil;
        
        // Only Difference between POST and GET is only in the way they send parameters
        
        if([method isEqualToString:@"GET"]){
            
            NSString *getURL = [NSString stringWithFormat:@"%@?username=%@&password=%@", URL, usrname, pass ];
            url = [NSURL URLWithString: getURL];
            request = [NSMutableURLRequest requestWithURL:url];
            
        }else{  // POST
            
            NSString *parameter = [NSString stringWithFormat:@"username=%@&password=%@",usrname, pass ];
            NSData *parameterData = [parameter dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
;
            url = [NSURL URLWithString: URL];
            request = [NSMutableURLRequest requestWithURL:url];
            [request setHTTPBody:parameterData];
        
        }
        
        [request setHTTPMethod:method];
        [request addValue: @"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
       
        NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
        
        if( connection )
        {
            
            mutableData = [NSMutableData new];
            
        }else{
            
            serverResponse.text = NO_CONNECTION;
            
        }
        
    }else{
        
        serverResponse.text = NO_VALUES;
        
    }
    
}

#pragma mark NSURLConnection delegates

-(void) connection:(NSURLConnection *) connection didReceiveResponse:(NSURLResponse *)response
{
    [mutableData setLength:0];
}

-(void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [mutableData appendData:data];
}

-(void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    serverResponse.text = NO_CONNECTION;
    return;
}

-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSString *responseStringWithEncoded = [[NSString alloc] initWithData: mutableData encoding:NSUTF8StringEncoding];
    //NSLog(@"Response from Server : %@", responseStringWithEncoded);
    NSAttributedString * attrStr = [[NSAttributedString alloc] initWithData:[responseStringWithEncoded dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil];
    serverResponse.attributedText = attrStr;
}

@end


Here is the server side PHP code that can handle both POST and GET Requests.
Since you are getting the values, You can modify this code to say check with the database and
send appropriate result.

Here I am just sending back the values send from the Client Side (From iPhone or any other device)

<?php

    echo " Response From Server Side";
    echo "Username : " . $_REQUEST['username'];
    echo "Password : " . $_REQUEST['password']; // Do any database operations here... 

?>

You can download the complete source code from here.

 

 

3 thoughts on “Send Data to server in iOS using POST OR GET – A Simple Example

  1. Pingback: NSURLConnection - A Simple example - Upload image to server using POST method.

  2. Pushpendra singh patel

    Sir, Send me a test.php file of this link
    “http://localhost/test.php” on my mail id .
    Thanks

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *