2011-12-21 49 views
0

我有問題,在我的應用程序中,我需要有一個連接和一個web視圖來顯示web內容。 問題是我有一個用戶名和密碼,需要正確才能獲得連接。現在,如果用戶名不正確,我想要提醒您。該webView和'超時'

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error 

不適合這個工作,因爲如果用戶名或密碼錯誤,將繼續加載(即使它不會顯示任何東西)。

是否有可能'告訴'webview設置時間間隔,然後顯示警報?

非常感謝!

+0

由服務器強制執行此密碼要求?如果是這樣,響應應該包含適當的錯誤,以便您處理並嚮應用用戶顯示適當的錯誤。 – XJones 2011-12-21 18:03:22

+0

不,密碼是這樣發送到服務器: http:// username:[email protected] 如果我在我的mac瀏覽器上輸入錯誤的用戶名/密碼,他會要求我重新輸入。這不適用於iPhone,所以我想有一個像'計時器' – user1110365 2011-12-21 23:28:34

回答

0

如果您通過HTTP身份驗證與您的服務器進行身份驗證(根據您的評論以上),那麼我會以不同的方式做到這一點。當用戶輸入他們的用戶名/密碼時,使用NSURLConnection向任何頁面(輕量級)發出請求。如果用戶名/密碼不正確,您可以在NSURLConnectionDelegate方法中處理失敗並提示用戶輸入新的用戶名/密碼。

您也可以使用iOS 5版本NSURLConnection而不是委託方法來做到這一點,但文檔不是很好。

當這第一個請求成功,然後加載網絡視圖。

編輯:使用NSURLConnection的檢查,如果HTTP認證成功

確定的追加例題,這裏有一個簡單的例子。您可以通過允許NSURLConnection加載您的預期請求,並且如果它成功將響應數據加載到webView與啓動新請求相比較,可以做得更好。閱讀URL加載系統文檔以瞭解更多關於如何使用NSURLConnection

在你webView委託,發起NSURLConnection與同一個域的請求爲webView請求與用戶憑據,如下所示:

- (void)performHTTPAuthRequest 
{ 
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://%@:%@@test.starsightings.com", username, password]]]; 
    NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self]; 
} 

// if the request succeeds, credentials must be good so load the webView 
- (void)connectionDidFinishLoading:(NSURLConnection *)connection 
{ 
    // request completed successfully so username/password must be good 
    [self.webView loadRequest:theRequest]; 
} 

// ignore the failure 
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error 
{ 
} 

// if we get an auth challenge, the credentials are bad so cancel the request and alert the user 
- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge 
{ 
    [[challenge sender] cancelAuthenticationChallenge:challenge]; 
    // alert user that username/pwd is invalid 
} 
+0

好吧,那麼你能解釋我該怎麼做嗎?因爲我不明白它:( – user1110365 2011-12-23 12:51:00

+0

完成。它不是那麼糟糕。 – XJones 2011-12-24 04:18:26

+0

謝謝:)我現在明白了! – user1110365 2011-12-25 00:43:34