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

时间:2024-05-01 16:08:05

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

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

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

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

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

.h 文件

1 #import "SDWebImageDownloader.h"

 @interface SDWebImageDownloader (AFNHttps)

 @end
 #import <SDWebImageDownloader.h>
#import "SDWebImageDownloader+AFNHttps.h" @implementation SDWebImageDownloader (AFNHttps) + (void)load {
     //设置SDWebImageDownloader的证书
[SDWebImageDownloader sharedDownloader].urlCredential = [self myUrlCredential];
} + (NSURLCredential *)myUrlCredential { NSString *thePath = [[NSBundle mainBundle] pathForResource:@"p12证书名" ofType:@"p12"];
//倒入证书 NSLog(@"thePath===========%@",thePath);
NSData *PKCS12Data = [[NSData alloc] initWithContentsOfFile:thePath];
CFDataRef inPKCS12Data = (__bridge CFDataRef)PKCS12Data; SecIdentityRef identity = NULL;
// extract the ideneity from the certificate
[self mosM_extractIdentity:inPKCS12Data toIdentity:&identity]; SecCertificateRef certificate = NULL;
SecIdentityCopyCertificate (identity, &certificate); return [NSURLCredential credentialWithIdentity:identity certificates:nil persistence:NSURLCredentialPersistencePermanent];;
} + (OSStatus)extractIdentity:(CFDataRef)inP12Data toIdentity:(SecIdentityRef*)identity {
OSStatus securityError = errSecSuccess;
CFStringRef password = CFSTR("p12证书密码");
const void *keys[] = { kSecImportExportPassphrase };
const void *values[] = { password };
CFDictionaryRef options = CFDictionaryCreate(NULL, keys, values, , NULL, NULL);
CFArrayRef items = CFArrayCreate(NULL, , , NULL);
securityError = SecPKCS12Import(inP12Data, options, &items);
if (securityError == )
{
CFDictionaryRef ident = CFArrayGetValueAtIndex(items,);
const void *tempIdentity = NULL;
tempIdentity = CFDictionaryGetValue(ident, kSecImportItemIdentity);
*identity = (SecIdentityRef)tempIdentity;
}
if (options) {
CFRelease(options);
}
return securityError;
}