我們在瀏覽器訪問https頁面的時候的,會彈出:

我們接下來信任證書以及顯示出來
遵循協議
~~~
@interface ViewController ()<NSURLConnectionDataDelegate>
~~~
interface:
~~~
@interface ViewController ()<NSURLConnectionDataDelegate>
/**
- 存儲data數據
*/
@property(nonatomic,strong)NSMutableData *dataM;
/**
- 訪問url鏈接
*/
@property(nonatomic,strong)NSURL *url;
@property(nonatomic,weak)IBOutlet UIWebView *webView;
@end
~~~
viewDidLoad:創建url以及發送請求
~~~
- (void)viewDidLoad {
[super viewDidLoad];
self.url = [NSURL URLWithString:@"https://mail.com"];
NSURLRequest *request = [NSURLRequest requestWithURL:self.url];
//發送請求
[NSURLConnection connectionWithRequest:request delegate:self];
}
~~~
實現代理方法:
~~~
#pragma mark - NSURLSessionDataDelegate代理方法
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task
didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge
completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential * __nullable credential))completionHandler
{
NSLog(@"challenge = %@",challenge.protectionSpace.serverTrust);
//判斷是否是信任服務器證書
if (challenge.protectionSpace.authenticationMethod ==NSURLAuthenticationMethodServerTrust)
{
//創建一個憑據對象
NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
//告訴服務器客戶端信任證書
[challenge.sender useCredential:credential forAuthenticationChallenge:challenge];
}
}
/**
* 接收到服務器返回的數據時調用
*/
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
NSLog(@"接收到的數據%zd",data.length);
[self.dataM appendData:data];
}
/**
* 請求完畢
*/
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSString *html = [[NSString alloc]initWithData:self.dataM encoding:NSUTF8StringEncoding];
NSLog(@"請求完畢");
[self.webView loadHTMLString:html baseURL:self.url];
}
~~~
懶加載:
~~~
- (NSMutableData *)dataM
{
if (_dataM == nil)
{
_dataM = [[NSMutableData alloc]init];
}
return _dataM;
}
~~~
至此,我們已經實現了https數據的展示:
**注意:**
NSURLSession/NSURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9843) 原因:沒有信任服務器證書
在下面這個方法中:
~~~
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task
didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge
completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential * __nullable credential))completionHandler()
~~~
我們通過protectionSpace.authenticationMethod判斷是否信任服務器證書
- NSURLSessionAuthChallengeUseCredential = 0, 使用憑據 ,信任服務器證書
- NSURLSessionAuthChallengePerformDefaultHandling = 1, 默認處理,忽略服務器證書
- NSURLSessionAuthChallengeCancelAuthenticationChallenge = 2, 整個請求被取消 憑據被忽略
- NSURLSessionAuthChallengeRejectProtectionSpace = 3, 本次拒絕,下次重試