Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

connection didReceiveData called twice while posting a Url in iphone?

I am new to iphone development.I have posted the URL with the user-name and password. I am able to print the data in "connection didReceiveData " method.But i see "connection didReceiveData" method called twice.I don't know ,where i am going wrong. Here is my code

 - (void)viewDidLoad {
[super viewDidLoad];

NSString *post = [NSString stringWithFormat:@"&domain=school.edu&userType=2&referrer=http://apps.school.edu/navigator/index.jsp&username=%@&password=%@",@"xxxxxxx",@"xxxxxx"];

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

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

NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];

[request setURL:[NSURL URLWithString:[NSString stringWithFormat:@"https://secure.school.edu/login/process.do"]]];

[request setHTTPMethod:@"POST"];

[request setValue:postLength forHTTPHeaderField:@"Content-Length"];

[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Current-Type"];

[request setHTTPBody:postData];

NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self];

if(conn)
{
    NSLog(@"Connection Successful");

}
else
{
    NSLog(@"Connection could not be made");
}

    }

 - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData*)data{

NSString *string = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
NSLog(@"the  data %@",string);
  }

The whole HTML page is printed twice in the console.So please help me out.Thanks.

like image 683
Warrior Avatar asked Mar 15 '10 09:03

Warrior


1 Answers

You may receive the response data in chunks, which is why NSURLConnection's documentation states:

"The delegate should concatenate the contents of each data object delivered to build up the complete data for a URL load."

Use an instance of NSMutableData for this and only process the complete data once you receive the -connectionDidFinishLoading: message.

like image 188
Alex Repty Avatar answered Sep 30 '22 11:09

Alex Repty