views:

220

answers:

1

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.

+6  A: 

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.

Alexander Repty
If you receive large amounts of data, you may want to look at NSFileHandler to write the chunks to the disk as they arrive. Otherwise NSMutableData should be fine, especially if you do not want to store the data anyway.
Felix
Good point, Felix - especially regarding the iPhone's limited memory.
Alexander Repty