2012-02-26 76 views
0

我試圖讓我的iOS應用程序使用基本身份驗證從我的本地apache服務器訪問文件。在瀏覽器中一切正常,我必須輸入我的用戶名和密碼才能訪問受限制文件夾中的圖像。但在應用程序中發生了一些奇怪的事情。iOS似乎繞過了基本的服務器身份驗證

我做了NSURLConnection到服務器(這一切都工作正常),並在我的請求第一次作出代理方法- (void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge被調用。出於測試目的,我回應一個空的NSURLCredential,顯然連接失敗。但是,當我再次發出請求時,委託方法不會被調用,並且不知何故,圖像會被下載並顯示,而無需任何身份驗證。對於發生了什麼,我感到非常困惑!

下面是一些代碼:

- (IBAction)loginPressed 
{ 
    self.username = self.usernameField.text; 
    self.password = self.passwordField.text; 
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://192.168.0.2/secret/favicon.ico"]]; 
    self.connection = [NSURLConnection connectionWithRequest:request delegate:self]; 
} 


- (void)connection:(NSURLConnection *)theConnection didReceiveData:(NSData *)data 
{ 
    [self.data appendData:data]; 
} 

- (void)connectionDidFinishLoading:(NSURLConnection *)connection 
{ 
    self.imageView.image = [UIImage imageWithData:self.data]; 
    self.errorLabel.text = @""; 
} 

- (void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge 
{ 
    if ([challenge previousFailureCount] == 0) { 
     NSURLCredential *newCredential = [NSURLCredential credentialWithUser:self.username password:self.password persistence:NSURLCredentialPersistenceNone]; 
     [challenge.sender useCredential:newCredential forAuthenticationChallenge:challenge]; 
    } else { 
     [challenge.sender cancelAuthenticationChallenge:challenge]; 
     self.errorLabel.text = @"Invalid Username and/or Password"; 
     self.imageView.image = [UIImage imageWithData:[[NSData alloc] init]]; 
    } 
} 
+0

請更多代碼。 – 2012-02-26 22:26:45

+0

這幾乎是所有使用的代碼。我通過登錄按鈕發送請求,當將textfields留空時,我得到了上述結果。 – 2012-02-26 22:34:16

+0

順便說一句,你的最後一行代碼泄漏。你正在創建一個'NSData'實例而不釋放它。除此之外,您可以將imageView圖像分配給'nil'。 – 2012-02-26 22:57:02

回答

3

您應該使用不同的委託回調,connection:didReceiveAuthenticationChallenge:

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

    if ([challenge previousFailureCount] > 0) { 
     // Do something, like prompt for credentials or cancel the connection 
    } else { 
     NSURLCredential *creds = [NSURLCredential 
          credentialWithUser:@"someUser" 
            password:@"somePassword" 
           persistence:NSURLCredentialPersistenceForSession]; 

     [[challenge sender] useCredential:creds forAuthenticationChallenge:challenge]; 
    } 
} 
+0

我仍然對應用程序如何實際下載圖像而不響應身份驗證挑戰感到困惑。新的委託方法發生完全相同的問題。 – 2012-02-26 23:02:31

+1

@ruhatch緩存的圖像?嘗試下載不同的圖像。 – 2012-02-26 23:08:31

+1

非常好,工作。我沒有改變請求的緩存策略,以避免將來出現這個問題。 – 2012-02-26 23:12:26