在加载网页之前调用NSURLConnection connectionDidFinishLoading

时间:2012-08-13 21:55:57

标签: objective-c ios cocoa-touch connection nsurlconnection

我刚开始进行iOS编程,但我无法理解这一点。我正在尝试连接到有登录的网站..我正在使用NSURLConnection和POST,并发送我的登录凭据..

凭据是正确的,并且connectionDidFinishLoading:被调用但它没有完全登录到站点..登录部分完成..当我查看响应时我发现了这一点..根据我的理解只有在连接完成后才会调用“connectionDidFinishLoading”..我在这里肯定遗漏了一些东西..我的代码在下面..请建议..

- (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];
}

这里,当我记录响应时,它是不完整的..它登陆在最终SUCCESS页面之间的页面中。所以身份验证部分完成..我是否需要包含任何延迟?请帮忙..

- (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);
}

提前致谢..

1 个答案:

答案 0 :(得分:0)

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response

请尝试使用此方法。根据文档,它是“当连接收到足够的数据来为其请求构建URL响应时发送。(必需)”