Iphone 如何在iOS中访问需要身份验证的URL

Iphone 如何在iOS中访问需要身份验证的URL,iphone,ios,url,Iphone,Ios,Url,目前,我正在iPhone应用程序中从URL加载一幅图像,效果很好。但是现在我想访问一个受保护的URL。请用一段代码指导我如何使用凭据(用户名/密码)访问URL 下面给出了我的应用程序从URL加载图像的简单代码 NSURL *url = [NSURL URLWithString: @"http://www.somedirectory.com"]; UIImage *image = [UIImage imageWithData: [NSData dataWithContentsOfU

目前,我正在iPhone应用程序中从URL加载一幅图像,效果很好。但是现在我想访问一个受保护的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];
    }
}

您可以使用类似的第三方库,这使它非常简单

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

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

我已经尝试过这个方法,但它没有调用didReceiveAuthenticationChallenge回调。