0

目前我正在我的 iPhone 应用程序中从 URL 加载图像,这工作正常。但现在我想访问受保护的 URL。请用一段代码指导我如何使用凭据(用户名/密码)访问 URL。

下面给出了我的应用程序从 URL 加载图像的简单代码

    NSURL *url = [NSURL URLWithString: @"http://www.somedirectory.com"];
    UIImage *image = [UIImage imageWithData: [NSData dataWithContentsOfURL:url]]; 
    [Pic setImage:image];
4

2 回答 2

1

寻找这两个回调

- (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];
    }
}
于 2012-05-21T11:43:25.463 回答
0

您可以使用一些第三方库,例如ASIHTTPRequest,这很容易。

NSURL *url = [NSURL URLWithString:@"http://allseeing-i.com/top_secret/"];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setUsername:@"username"];
[request setPassword:@"password"];

或者您可以使用NSURLConnection类,但身份验证实现有点棘手。

于 2012-05-21T11:45:45.890 回答