Wednesday, October 23, 2013

Posting data to server using NSURLConnection



I am here to write a small article on how to post the data to server and how to handle the response on the same.

First lets have some basic idea about server like..i meant web service methods.I prefer to use REST API in this modern era.To start with On the server side,create the REST api(i prefer php) bridge such that you can able to access the server database/xml/json.To start with,lets make login authentication test using POST method(i prefer this because its more secured).


NSString *post_Details =[[NSString alloc] initWithFormat:@"user_name=%@&password=%@",user_name,password];
//user_name and password are the key names i have mentioned in my php code

    NSURL *ur_Url =[NSURL URLWithString:@"http://xxx.com/urAuthenticationMethod"];

    NSData *post_DetailsData = [post_Details dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];

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

    NSMutableURLRequest *post_Request = [[NSMutableURLRequest alloc] init];
    [post_Request setURL:ur_Url];
    [post_Request setHTTPMethod: @"POST"];
    [post_Request setValue: postLength forHTTPHeaderField: @"Content-Length"];
    [post_Request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
   //in which format you would like to accept the data.Like xml,json etc.

    [post_Request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    [post_Request setHTTPBody:post_DetailsData];

    NSError *error;
    NSURLResponse *_response;

  //I will be using Synchronous way of sending the data to server here.

    NSData *result_Data = [NSURLConnection sendSynchronousRequest:post_Request returningResponse:&_response error:&error];
    if (!result_Data)
    {
        NSLog(@"Error");
    }
    else
    {
        id json = [NSJSONSerialization JSONObjectWithData:result_Data options:kNilOptions error:&error];
        NSLog(@"Data: %@", json);
        if([json isKindOfClass:[NSArray class]])
        {
           //json is of type NSArray
            NSArray  *urArray = [json valueForKey:@"urKey"];

        }
        else if([json isKindOfClass:[NSDictionary class]])
        {
          //handle the dictionary same like array

        }
    }

Hope it helps you...Happy coding :-)



No comments:

Post a Comment