从https链接获取图像 [英] fetching an image from a https link
问题描述
我刚刚开始学习ios开发,我正在尝试从使用ssl的网站获取图像,当我通过浏览器(笔记本电脑)连接到该网站时,会出现一条警告,指出根证书不受信任,我不是网站的所有者,但我完全可以信任它。
我的第一次尝试:
I have just started learning ios development, and I am trying to get an image from website which uses ssl, when i connect to the site through a browser(laptop) there is a warning which says that the root certificate is not trusted, I am not the owner of the website, however I can fully trust it. My first attempt:
self.eventImage.image = [UIImage imageWithData:
[NSData dataWithContentsOfURL:
[NSURL URLWithString:imageUrl]]];
所以我收到此错误
NSURLConnection / CFURLConnection HTTP加载失败(kCFStreamErrorDomainSSL,-9807)
NSURLConnection/CFURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9807)
我试图向用户发送图片通过启动ios网络浏览器链接,当他们这样做时,他们会收到一条消息,询问他们是否可以信任,如果他们点击是,图像就会出现,但我希望图像出现在应用程序内。
I have tried to send users to the picture link by starting ios web browser, when they do that, they would get a message asking them if they could trust it or not, if they hit yes the image will appear, however i want the image to appear inside the application.
我也试过使用网页浏览但不起作用。
I have also tried to use web view but it didn't work.
这里建议的大多数类似问题使用这个
Most of the similar questions in here suggested using this
- (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];
}
但是我添加它们时从未调用过这两种方法。
but these two methods were never called when I add them.
推荐答案
更改您的代码。而不是使用 NSData dataWithContentsOfURL:
,您需要使用自己的显式 NSURLConnection
。然后你可以使用适当的 NSURLConnectionDelegate
方法。
Change your code. Instead of using NSData dataWithContentsOfURL:
you need to use your own explicit NSURLConnection
. Then you can make use of the appropriate NSURLConnectionDelegate
methods.
另一种选择是使用流行的 AFNetworking library 。
Another option is to use the popular AFNetworking library.
这篇关于从https链接获取图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!