2013-10-11 128 views
0

只是一個快速的一個,我怎樣檢測,如果登錄失敗,這裏是我的代碼:檢測網站登錄失敗objective-c?

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

我甚至不知道從哪裏開始就這一個是有一個委託方法來檢測這樣的行動?

+0

UIWebView在存儲憑證時可能會遇到問題,甚至可能不支持身份驗證(還)。如果可能,您可以下載數據並在之後爲WebView進行設置。 – CouchDeveloper

回答

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

0

如果你真的想用UIWebView來做,你可以使用它的委託方法和解析你網站的代碼。

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