AF3.0
//添加证书
- (AFSecurityPolicy *)customSecurityPolicy {
// /先导入证书
NSString *cerPath = [[NSBundle mainBundle] pathForResource:@"aichewang.cer" ofType:nil]; //证书的路径
NSData *certData = [NSData dataWithContentsOfFile:cerPath];
// AFSSLPinningModeCertificate 使用证书验证模式
AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate];
// allowInvalidCertificates 是否允许无效证书(也就是自建的证书),默认为NO
// 如果是需要验证自建证书,需要设置为YES
securityPolicy.allowInvalidCertificates = YES;
// validatesDomainName 是否需要验证域名,默认为YES;
//假如证书的域名与你请求的域名不一致,需把该项设置为NO;如设成NO的话,即服务器使用其他可信任机构颁发的证书,也可以建立连接,这个非常危险,建议打开。
//置为NO,主要用于这种情况:客户端请求的是子域名,而证书上的是另外一个域名。因为SSL证书上的域名是独立的,假如证书上注册的域名是www.google.com,那么mail.google.com是无法验证通过的;当然,有钱可以注册通配符的域名*.google.com,但这个还是比较贵的。
//如置为NO,建议自己添加对应域名的校验逻辑。
securityPolicy.validatesDomainName = NO;
securityPolicy.pinnedCertificates = [[NSSet alloc] initWithObjects:certData, nil];
return securityPolicy;
}
eg:
_sessionManager = [AFHTTPSessionManager manager];
// [_sessionManager setSecurityPolicy:[self customSecurityPolicy]];
WKWebView
设置代理navigationDelegate
// https 支持
- (void)webView:(WKWebView *)webView didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential * _Nullable credential))completionHandler{
if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
NSURLCredential *card = [[NSURLCredential alloc]initWithTrust:challenge.protectionSpace.serverTrust];
completionHandler(NSURLSessionAuthChallengeUseCredential,card);
}
}
SDWebImage
options : SDWebImageAllowInvalidSSLCertificates
通过runtime 方法交换
import "UIImageView+JFHttps.h"
#import <UIImageView+WebCache.h>
#import <objc/runtime.h>
@implementation UIImageView (JFHttps)
+ (void)load {
Class myClass = [self class];
// 获取SEL
SEL originSetImageSel = @selector(sd_setImageWithURL:placeholderImage:options:progress:completed:);
SEL newSetImageSel = @selector(sd_setHttpsImageWithURL:placeholderImage:options:progress:completed:);
// 生成Method
Method originMethod = class_getInstanceMethod(myClass, originSetImageSel);
Method newMethod = class_getInstanceMethod(myClass, newSetImageSel);
// 交换方法实现
method_exchangeImplementations(originMethod, newMethod);
}
- (void)sd_setHttpsImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletionBlock)completedBlock {
NSLog(@"这里实现了");
[self sd_setHttpsImageWithURL:url placeholderImage:placeholder options:SDWebImageAllowInvalidSSLCertificates progress:progressBlock completed:completedBlock];
}
@end