开发者

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)connect开发者_如何学编程ion:(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.


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.


As MacOS Developer Library states, connection:didReceiveData can be called multiple times if data is received in chunks. That means you have to save all the chunks in some variable and do data processing in connectionDidFinishLoading method. e.g.

NSMutableData *receivedData = [[NSMutableData alloc] init];

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    // Append the new data to receivedData.
    [receivedData appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    // do something with the data, for example log:
    NSLog(@"data: %@", [[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding]
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜