- - (void)viewDidLoad {
- [super viewDidLoad];
- // Do any additional setup after loading the view from its nib.
- //1,不帶證書的請求,有時候不用安裝,原因有二:可能以前裝過,或者有些大網站不用安裝
- // NSURLSessionTask *task = [[NSURLSession sharedSession]dataTaskWithURL:[NSURL URLWithString:@"https://developer.apple.com/"] completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
- // //
- //
- // NSLog(@"error:%@",error);
- // NSLog(@"data:%@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);
- // }];
- // [task resume];
- //2,程式自動安裝證書的方式
- NSURLSession *sesson = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc]init]];
- NSURLSessionTask *task = [sesson dataTaskWithURL:[NSURL URLWithString:@"https://xxx/json"] completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
- //
- NSLog(@"error:%@",error);
- NSLog(@"data:%@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);
- }];
- [task resume];
- }
- #pragma mark -----NSURLSessionTaskDelegate-----
- //NSURLAuthenticationChallenge 中的protectionSpace對象存放了伺服器傳回的證書資訊
- //如何處理證書?(使用、忽略、拒絕。。)
- - (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable))completionHandler//通過調用block,來告訴NSURLSession要不要收到這個證書
- {
- //(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable))completionHandler
- //NSURLSessionAuthChallengeDisposition (枚舉)如何處理這個證書
- //NSURLCredential 授權
- //證書分為好幾種:伺服器信任的證書、輸入密碼的證書 。。,是以這裡最好判斷
- if([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]){//伺服器信任證書
- NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];//伺服器信任證書
- if(completionHandler)
- completionHandler(NSURLSessionAuthChallengeUseCredential,credential);
- }
- NSLog(@"....completionHandler---:%@",challenge.protectionSpace.authenticationMethod);
- }