When we use https to make network requests, we will receive the certificates from the server. These certificates are divided into agency certificates and certificates issued by ourselves. In ios, if we are going to request an organization certified to send an https request, we don't need to process it. But if it is a self signed certificate, we have to process it, otherwise we won't get the data. So we need to deal with it in a proxy method
In the following proxy method, the following challenge.protectionSpace represents a secure space.//Create Session first NSURLSession * session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]]; //Build task NSURLSessionDataTask * task = [session dataTaskWithURL:[NSURL URLWithString:@"https://www.apple.com"] completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) { NSLog(@"%@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]); }]; //Perform task [task resume];
Where about nsurlsessionautchallengedisposition is an enumeration with the following enumeration values-(void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler: (void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable))completionHandler { //1. Judge whether the authentication method adopted by the server is: trust the server certificate if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) { //2. Create authentication certificate NSURLCredential * credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]; //3. Handling if(completionHandler) { //UseCredential represents the certificate sent back by the server completionHandler(NSURLSessionAuthChallengeUseCredential,credential); } } }
NSURLSessionAuthChallengeDisposition (Management): NSURLSessionAuthChallengeUseCredential - Use server to send back certificate(Save in challenge inside) NSURLSessionAuthChallengePerformDefaultHandling - Default handling,Certificate ignored NSURLSessionAuthChallengeCancelAuthenticationChallenge - Cancel entire request,Ignore certificate NSURLSessionAuthChallengeRejectProtectionSpace - This rejection,try again