Friday, 3 June 2011

Post Data to FTP Server

After trying to post data's to server, i found simple steps to understanding the concept of posting the data, this will be use when you needs to send any datas to your server. 

For instance to understand. Let us say when you about to send username and password to server while login.

//String to be post.
NSString *post = [NSString stringWithFormat:@"&Username=%@&Password=%@",@"username",@"password"];   
//Encode the post string to NSData with NSASCIIStringEncoding

NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
//Send the actual lenght of your data
NSString *postLength = [NSString stringWithFormat:@"%d",[postData length]];
//Create the urlrequest with all properties Http method and header field with length of the post string

NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
//Set your FTP server url
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://yourserver/details.php"]]];//set HTTP methods (Post or Get)[request setHTTPMethod:@"POST"];

//Set HTTP header field with length of the post data.
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
//Also set the Encoded value for HTTP header Field.
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Current-Type"];
//Set the HTTPBody of the urlrequest with postData.
[request setHTTPBody:postData];

 Now, create URLConnection object. Initialize it with the URLRequest.
NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self];

At last use the NSURLConnection delegates.