目前,我正在 iPhone 应用程序中从 URL 加载图像,工作正常。但现在我想访问 protected URL。请用一段代码指导我如何使用凭据(用户名/密码)访问 URL。
下面给出了我的应用程序从 URL 加载图像的简单代码
NSURL *url = [NSURL URLWithString: @"http://www.somedirectory.com"];
UIImage *image = [UIImage imageWithData: [NSData dataWithContentsOfURL:url]];
[Pic setImage:image];
最佳答案
寻找这两个回调
- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace
{
// IF to handle NTLM authentication.
if([[protectionSpace authenticationMethod] isEqualToString:NSURLAuthenticationMethodNTLM])
return YES;
// Mostly sent by IIS.
if([[protectionSpace authenticationMethod] isEqualToString:NSURLAuthenticationMethodServerTrust])
return YES;
return NO;
}
- (void) connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge*)challenge
{
if ([[[challenge protectionSpace] authenticationMethod] isEqual:NSURLAuthenticationMethodNTLM])
{
[[challenge sender] useCredential:[NSURLCredential
credentialWithUser:Username
password:password
persistence:NSURLCredentialPersistenceNone]
forAuthenticationChallenge:challenge];
}
else if ([[[challenge protectionSpace] authenticationMethod] isEqual:NSURLAuthenticationMethodServerTrust])
{
[[challenge sender] useCredential:[NSURLCredential
credentialWithUser:Username
password:password
persistence:NSURLCredentialPersistenceNone]
forAuthenticationChallenge:challenge];
}
else
{
[challenge.sender continueWithoutCredentialForAuthenticationChallenge:challenge];
}
}
关于iphone - iOS中如何访问需要认证的URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10684448/