检测网站登录是否失败objective-c?

时间:2013-10-11 19:08:13

标签: ios objective-c login

如何快速检测登录失败是否是我的代码:

- (IBAction)btnTimetable:(id)sender {
    NSString *user = _txtUsername.text;
    NSString *pass = _txtPassword.text;
    NSString *content = [NSString stringWithFormat:@"username=%@&password=%@", user, pass];
    NSData *data =[content dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
    NSString *postlenght=[NSString stringWithFormat:@"%lu",(unsigned long)[data length]];

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://moodle.thomroth.ac.uk/login/index.php?mode=login"]];
    [request setHTTPMethod:@"POST"];
    [request setValue:postlenght forHTTPHeaderField:@"Content-Length"];
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Length"];
    [request setHTTPBody:data];
    //NSError *error=nil;
    //NSURLResponse *response=nil;
    //NSData *result=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

    [_webView loadRequest:request];
    [self performSelector:@selector(parseTimetable) withObject:nil afterDelay:3.0];
}

我甚至不知道从哪里开始是否有委托方法来检测此类行为?

2 个答案:

答案 0 :(得分:0)

正如官方开发者论坛所述,UIWebView不支持iOS中的身份验证挑战。请在此处阅读(需要开发者帐户):UIWebView does not directly support authentication challenges

sendSynchronousRequest:returningResponse:error:应该返回nil,并且返回的响应的状态代码应该等于401(未经授权):

[(NSHTTPURLRequest*)response statusCode] == 401

我猜,错误参数应设置为相应的错误(请通过将其打印到控制台来检查)。

如果使用NSURLConnection的委托方法,情况就不同了:

NSURLConnection收到401时(例如,连接需要凭据进行身份验证,或先前的身份验证尝试失败),它会调用委托

- (void)connection:(NSURLConnection *)connection
  willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge;

如果实现,否则它会调用这些(现在被认为是过时的方法):

- (BOOL)connection:(NSURLConnection *)connection 
    canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace;

- (void)connection:(NSURLConnection *)connection 
    didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge;

- (BOOL)connectionShouldUseCredentialStorage:(NSURLConnection *)connection;

如果实施。

官方文档提供了更多信息:NSURLConnectionDelegate Protocol Reference

如果您决定取消身份验证请求,则可以取消该身份验证请求。因此,连接可能会失败。

如果连接失败,将调用connection:didFailWithError

答案 1 :(得分:0)

如果您真的想使用UIWebView,可以使用它的委托方法并解析您网站的代码答案。

- (void)webViewDidFinishLoad:(UIWebView *)webView {
    NSString *webSource = [_web stringByEvaluatingJavaScriptFromString:@"document.body.innerHTML"];
}