我試圖讓我的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]];
}
}
請更多代碼。 – 2012-02-26 22:26:45
這幾乎是所有使用的代碼。我通過登錄按鈕發送請求,當將textfields留空時,我得到了上述結果。 – 2012-02-26 22:34:16
順便說一句,你的最後一行代碼泄漏。你正在創建一個'NSData'實例而不釋放它。除此之外,您可以將imageView圖像分配給'nil'。 – 2012-02-26 22:57:02