I just started iOS programming and am failing to understand this.. I am trying to connect to a website that has a login.. I am using NSURLConnection and POST, and sending my login credentials..
The credentials are right and the connectionDidFinishLoading: is called but it is not completely logged into the site.. the login is partially complete..I identified this when I looked at the response.. As per my understanding the “connectionDidFinishLoading” is called only after the connection is complete.. I am definitely missing something here.. My code is below.. Please advice..
- (IBAction)connect:(id)sender {
// Login to the website
urlRequest=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://www.mywebsite.com/login"]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
NSString *post = @"username=myname&password=mypassword";
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
[urlRequest setHTTPMethod:@"POST"];
[urlRequest setValue:postLength forHTTPHeaderField:@"Content-Length"];
[urlRequest setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[urlRequest setHTTPBody:postData];
// Start the connection request
urlConnection = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self];
}
Here, when I log the response, it is incomplete.. It is landing in a page that is between the final SUCCESS page.. So the authentication is partially complete..Do I need to include any delay? Please help..
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSLog(@"Connection success.");
NSURLResponse *responseTest;
NSError *error;
NSData *responseDataTest = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&responseTest error:&error];
NSString *responsestring = [[NSString alloc] initWithData:responseDataTest encoding:NSASCIIStringEncoding];
NSLog(@"Recieved response.. %@",responsestring);
}
Thanks in advance..
Try using this method instead. According to the docs it is “Sent when the connection has received sufficient data to construct the URL response for its request. (required)”