0

ログインが失敗したかどうかを検出する方法を簡単に説明します。ここに私のコードがあります。

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

このようなアクションを検出するデリゲート メソッドはありますか?

4

2 に答える 2

0

公式の開発者フォーラムで述べられているように、UIWebView は iOS での認証チャレンジをサポートしていません。こちらをお読みください (開発者アカウントが必要です): UIWebView は認証チャレンジを直接サポートしていません

sendSynchronousRequest:returningResponse:error:返される必要があり、返された応答のステータス コードは(Unauthorized)nilに等しい必要があります。401

[(NSHTTPURLRequest*)response statusCode] == 401

エラーパラメータは対応するエラーに設定する必要があると思います(コンソールに出力して確認してください)。

状況のデリゲート アプローチを使用する場合NSURLConnectionは異なります。

401 を受信した場合NSURLConnection(たとえば、接続に認証用の資格情報が必要である、または以前の認証試行が失敗した場合)、デリゲートを呼び出します。

- (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呼び出されます。

于 2013-10-11T19:56:00.443 に答える