SDWebImage 加载Https自签名证书时的图片问题

Posted SUPER_F

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SDWebImage 加载Https自签名证书时的图片问题相关的知识,希望对你有一定的参考价值。

你是否遇到了这种情况,好不容易把自签名HTTPS证书配置好了,访问https接口也成功了,但是图片加载不出来?

传了SDWebImageAllowInvalidSSLCertificates 还是没效果没效果(这种情况只适用于CA我觉得),

并且一直 HTTP load failed (error code: -999 [1:89]),

经过不懈努力,终于找到了在不修改SDWebimageDownloader.m源码的情况下的解决方案;

通过创建SDWebimageDownloader的分类来实现,如下:

.h 文件

1
#import "SDWebImageDownloader.h" 2 3 @interface SDWebImageDownloader (AFNHttps) 4 5 @end

 

 1 #import <SDWebImageDownloader.h>
 2 #import "SDWebImageDownloader+AFNHttps.h"
 3 
 4 @implementation SDWebImageDownloader (AFNHttps)
 5 
 6 + (void)load {
     //设置SDWebImageDownloader的证书
7 [SDWebImageDownloader sharedDownloader].urlCredential = [self myUrlCredential]; 8 } 9 10 + (NSURLCredential *)myUrlCredential { 11 12 NSString *thePath = [[NSBundle mainBundle] pathForResource:@"p12证书名" ofType:@"p12"]; 13 //倒入证书 NSLog(@"thePath===========%@",thePath); 14 NSData *PKCS12Data = [[NSData alloc] initWithContentsOfFile:thePath]; 15 CFDataRef inPKCS12Data = (__bridge CFDataRef)PKCS12Data; 16 17 SecIdentityRef identity = NULL; 18 // extract the ideneity from the certificate 19 [self mosM_extractIdentity:inPKCS12Data toIdentity:&identity]; 20 21 SecCertificateRef certificate = NULL; 22 SecIdentityCopyCertificate (identity, &certificate); 27 28 return [NSURLCredential credentialWithIdentity:identity certificates:nil persistence:NSURLCredentialPersistencePermanent];; 29 } 30 31 32 + (OSStatus)extractIdentity:(CFDataRef)inP12Data toIdentity:(SecIdentityRef*)identity { 33 OSStatus securityError = errSecSuccess; 34 CFStringRef password = CFSTR("p12证书密码"); 35 const void *keys[] = { kSecImportExportPassphrase }; 36 const void *values[] = { password }; 37 CFDictionaryRef options = CFDictionaryCreate(NULL, keys, values, 1, NULL, NULL); 38 CFArrayRef items = CFArrayCreate(NULL, 0, 0, NULL); 39 securityError = SecPKCS12Import(inP12Data, options, &items); 40 if (securityError == 0) 41 { 42 CFDictionaryRef ident = CFArrayGetValueAtIndex(items,0); 43 const void *tempIdentity = NULL; 44 tempIdentity = CFDictionaryGetValue(ident, kSecImportItemIdentity); 45 *identity = (SecIdentityRef)tempIdentity; 46 } 47 if (options) { 48 CFRelease(options); 49 } 50 return securityError; 51 }

 




以上是关于SDWebImage 加载Https自签名证书时的图片问题的主要内容,如果未能解决你的问题,请参考以下文章

JavaFx Webview JDK 8 无法加载自签名证书

OpenSSL生成HTTPS自签名证书

NSURLSession "HTTP 加载失败 kCFStreamErrorDomainSSL, -9813 ; 自签名证书

wget、自签名证书和自定义 HTTPS 服务器

生成自签名ca 证书 使nginx 支持https

Https自签名证书认证及数据请求的封装