Wednesday, August 15, 2012

Web Server connection from iOS Application

In this  section , i will be describing how to access and update the data from/to web server backend. General scenario for this section is that, iOS device has the front end GUI for data visualization and we gonna fetch the data from backend database which is simply web server  and we will format the reponse data using JSON Library.
At first, we need to download JSON Library from https://github.com/downloads/stig/json-framework/JSON%20v3.0beta2%20(iOS).zip  . Unzip it and drag the JSON "Classes" folder to your running project. Now import  #import "JSON.h" and  #import "SBJson.h"
There are two ways of accessing the data  from web server: HTTP Post and Get method. HTTP Post is more secure way so i will prefer you to use Post method.

HTTP POST Method and JSON Formatting

1. Preparing HTTP Post data :
      NSString *jsonRequest_PRE,*jsonRequest,*fixedURL;
    // prapare the parameter you want to send in server, here eg: username and password
      jsonRequest_PRE =    [NSString stringWithFormat:@"username=%@ password=%@",tempUserName,tempPassword];
      jsonRequest =    [jsonRequest_PRE    stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
      // Now, load your URL for server
        fixedURL = [@"Your Server Url" stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
      // Now, praparing the complete HTTP request data
    NSURL *url = [NSURL URLWithString:fixedURL];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url cachePolicy:1 timeoutInterval:30];
     NSData *requestData = [NSData dataWithBytes:[jsonRequest UTF8String] length:[jsonRequest length]];
     [request setHTTPMethod:@"POST"];
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    [request setValue:@"close" forHTTPHeaderField:@"Connection"];
    [request setValue:[NSString stringWithFormat:@"%d", [requestData length]] forHTTPHeaderField:@"Content-Length"];
    [request setHTTPBody: requestData]; // loading your parameter as a HTTP body


2. Sending Server request and json formatting of its response
    NSURLResponse *response = nil;
    NSError *error = nil;
   // sending synchronous web call
    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
   NSString *returnString = [[NSString alloc] initWithData:data encoding: NSUTF8StringEncoding] ;
    SBJSON *json = [[SBJSON new]autorelease];
   // read the formatted  response data in dictionary or string as per your data structure
    NSDictionary *responseDict = [json objectWithString:returnString error:&error];
    // Now, check whether response is arrived or not ?
    if (responseDict == nil) {
    // No response
        NSLog(@"Error Synchrnous: %@",[error localizedDescription]);
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Error!" message:@"WEBSERVER_CONNFAIL" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
        [alert show];
    }
else {
     /// Your response date is here. Start formatting with it for your app.  
}

HTTP GET Method and JSON Formatting

 1. Prepare HTTP Get data :
    -include <NSURLConnectionDelegate>
    - define and synthesize NSMutabaleData *responseData;
    in viewDidLoad :
    NSString *urlString = [NSString stringWithFormat:@"http://testServerUrl.com/login.json?username=samir&password=jwarchan"];
   responseData = [[NSMutableData alloc] init];
  NSURL *url = [NSURL URLWithString:urlString];
  NSURLRequest *request = [[NSURLRequest alloc] initWithURL: url];
 // Asynchronous web call, needs delegate methods
  NSURLConnection  *connection = [[NSURLConnection alloc] initWithRequest: request delegate: self];

2. Now, handling  delegate methods for Asynchronous web call :
-->
 - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {  
         [responseData setLength:0];
 } 
 - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {      
          [responseData appendData:data]; 
}   
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {   
      responseData = nil;
    // display error alert
 }
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
 
-->NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
 // create dictionary or string from Json string as per your data structure
 NSDictionary *result = [responseString JSONValue] ;
  if(result != nil) {
  // Proceed your  response data
}
// for better json customizing with error handling, use the same json fomating code as in above (as for in HTTP Post method)
}


No comments:

Post a Comment