【发布时间】:2012-06-06 02:16:57
【问题描述】:
我正在尝试让我的 iOS 应用使用基本身份验证从本地 apache 服务器访问文件。浏览器一切正常,我必须输入我的用户名和密码才能访问受限文件夹中的图像。然而,在应用程序中发生了一些奇怪的事情。
我向服务器创建了一个 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]];
}
}
【问题讨论】:
-
这就是几乎所有使用的代码。我正在通过登录按钮发送请求,并且在将文本字段留空时得到了上面的结果。
-
顺便说一句,您的最后一行代码泄漏了。您正在创建一个
NSData实例而不释放它。除此之外,您只需将 imageView 图像分配给nil。
标签: objective-c ios apache http basic-authentication