ios - 从 https 链接获取图像

标签 ios ssl https

我刚开始学习 ios 开发,我试图从使用 ssl 的网站获取图像,当我通过浏览器(笔记本电脑)连接到该网站时,出现一条警告,指出根证书不受信任,我不是该网站的所有者,但我可以完全信任它。 我的第一次尝试:

self.eventImage.image = [UIImage imageWithData:
[NSData dataWithContentsOfURL:
[NSURL  URLWithString:imageUrl]]];

所以我得到这个错误

NSURLConnection/CFURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9807)

我试图通过启动 ios 网络浏览器将用户发送到图片链接,当他们这样做时,他们会收到一条消息,询问他们是否可以信任它,如果他们点击是,图像将会出现,但是我希望图像出现在应用程序中。

我也尝试过使用 WebView ,但没有成功。

这里的大多数类似问题都建议使用这个

- (BOOL)connection:(NSURLConnection *)
  connection canAuthenticateAgainstProtectionSpace: 
  (NSURLProtectionSpace *)protectionSpace {
    return NO;
    //return [protectionSpace.authenticationMethod isEqualToString:
    //         NSURLAuthenticationMethodServerTrust];
}

- (void)connection:(NSURLConnection *)
  connection didReceiveAuthenticationChallenge:
  (NSURLAuthenticationChallenge *)challenge {
     NSString *imageUri =[self.detailItem objectForKey: @"image"];
     NSArray *trustedHosts = [[NSArray alloc]initWithObjects:imageUri, nil];
     if ([challenge.protectionSpace.authenticationMethod   
         isEqualToString:NSURLAuthenticationMethodServerTrust])
        if ([trustedHosts containsObject:challenge.protectionSpace.host])
               [challenge.sender useCredential:[NSURLCredential credentialForTrust:
                challenge.protectionSpace.serverTrust] forAuthenticationChallenge:
                challenge];

 [challenge.sender continueWithoutCredentialForAuthenticationChallenge:challenge];
}

但这两个方法在我添加它们时从未被调用。

最佳答案

尝试添加这两个方法

- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace {
return [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust];
}

-(void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
[challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge];
[challenge.sender continueWithoutCredentialForAuthenticationChallenge:challenge];
}

关于ios - 从 https 链接获取图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19941939/

相关文章:

PHP Curl 连接至 Amazon MWS 卖家 API

带 header 的 Ruby https POST

ssl - OpenShift + Istio 中的 mTLS(客户端证书)

android - React Native 实时获取数据

ios - 与 -bitcode_bundle 一起使用时,-headerpad_max_install_names 将被忽略

ios - 为iOS编译时,如何让Unity自动添加“使用Apple登录”功能?

PHP CURL "NSS: client certificate not found (nickname not specified)"问题

ios - CGPDFDocument线程

php - 推送通知 (iPhone) 给出 "111 Connection refused"

android - 使用 SSLServerSocket 和 SSLSocket 通信时是否需要实现证书?