iphone - iOS中如何访问需要认证的URL

标签 iphone ios url

目前,我正在 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/

相关文章:

ios - @2x 和@3x 像素问题

iphone - ViewController 不调用 deinit 方法 swift 4

ios - 使用 ReactiveCocoa 从 View 模型更新 UITableViewCell

javascript - Laravel:我在 Controller 中编写的 URL 在 View 中不起作用

ios - 如何为 CallKit 来电 UI 设置超时

iphone - 更改 mp3 文件的节奏\bpm

iphone - 目标日期 2 天前的 NSNotification

html - IOS上下巨大空间渲染的SVG图片

c# - 如何使用默认浏览器打开具有基本授权的网址?

ios - URL 中的parameterString NSURL 的等效项