最近碍现,我剛剛把http 轉(zhuǎn)化為https具滴,給還在糾結(jié)中的朋友們指導一二士嚎。
1呜魄、準備證書
首先找后臺要一個證書(SSL證書,一般你跟后臺說要弄https,然后讓他給你個證書莱衩,他就知道了)爵嗅,我們需要的是.cer的證書。但是后臺可能給我們的是.crt的證書笨蚁。我們需要轉(zhuǎn)換一下:打開終端 -> cd到.crt證書路徑 -> 輸入openssl x509 -in 你的證書.crt -out 你的證書.cer -outform der睹晒,證書就準備好了,拖入工程括细,記得選copy伪很。
2、修改AFN中問題奋单,我看網(wǎng)上有新建一個類或類方法的
我是在AFHTTPSessionManager這個類中- (instancetype)initWithBaseURL:(NSURL *)url sessionConfiguration:(NSURLSessionConfiguration *)configuration 方法中直接添加的
__weak typeof(self) weakSelf = self;
[self setSessionDidReceiveAuthenticationChallengeBlock:^NSURLSessionAuthChallengeDisposition(NSURLSession *session, NSURLAuthenticationChallenge *challenge, NSURLCredential *__autoreleasing *_credential) {
/// 獲取服務(wù)器的trust object
SecTrustRef serverTrust = [[challenge protectionSpace] serverTrust];
// 導入自簽名證書
//#warning 注意將你的證書加入項目锉试,并把下面名稱改為自己證書的名稱
NSString *cerPath = [[NSBundle mainBundle] pathForResource:@"證書名字" ofType:@"cer"];
NSData* caCert = [NSData dataWithContentsOfFile:cerPath];
if (!caCert) {
NSLog(@" ===== .cer file is nil =====");
return nil;
}
NSSet *cerArray =[NSSet setWithObject:caCert];
weakSelf.securityPolicy.pinnedCertificates = cerArray;
SecCertificateRef caRef = SecCertificateCreateWithData(NULL, (__bridge CFDataRef)caCert);
NSCAssert(caRef != nil, @"caRef is nil");
NSArray *caArray = @[(__bridge id)(caRef)];
NSCAssert(caArray != nil, @"caArray is nil");
// 將讀取到的證書設(shè)置為serverTrust的根證書
OSStatus status = SecTrustSetAnchorCertificates(serverTrust, (__bridge CFArrayRef)caArray);
SecTrustSetAnchorCertificatesOnly(serverTrust,NO);
NSCAssert(errSecSuccess == status, @"SecTrustSetAnchorCertificates failed");
//選擇質(zhì)詢認證的處理方式
NSURLSessionAuthChallengeDisposition disposition = NSURLSessionAuthChallengePerformDefaultHandling;
__autoreleasing NSURLCredential *credential = nil;
//NSURLAuthenticationMethodServerTrust質(zhì)詢認證方式
if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
//基于客戶端的安全策略來決定是否信任該服務(wù)器,不信任則不響應(yīng)質(zhì)詢览濒。
if ([weakSelf.securityPolicy evaluateServerTrust:challenge.protectionSpace.serverTrust forDomain:challenge.protectionSpace.host]) {
//創(chuàng)建質(zhì)詢證書
credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
//確認質(zhì)詢方式
if (credential) {
disposition = NSURLSessionAuthChallengeUseCredential;
} else {
disposition = NSURLSessionAuthChallengePerformDefaultHandling;
}
} else {
//取消挑戰(zhàn)
disposition = NSURLSessionAuthChallengeCancelAuthenticationChallenge;
}
} else {
disposition = NSURLSessionAuthChallengePerformDefaultHandling;
}
return disposition;
}];
如果你的項目中不含有webView wkWebView? 呆盖,將這個設(shè)置為NO或者刪掉,但是如果含有哪兩種的話贷笛,建議參考這個http://www.wosign.com/faq/faq-ios10-ats.htm
如果有不對的地方請多指教应又。。昨忆。丁频。。