SoFunction
Updated on 2025-04-13

IOS development supports https requests and SSL certificate configuration details

IOS development supports https requests and SSL certificate configuration details

Preface:

As we all know, Apple has said that starting from 2017, it will block http resources and force https

The poster happened to convert http to https recently and share it with friends who have not started yet.

1. Certificate preparation

1. Certificate conversion

After the server staff sends you the crt certificate, enter the certificate path and execute the following statement

// openssl x509 -in your certificate.crt -out your certificate.cer -outform der

This way you can get a certificate of type cer. Double-click to import the computer.

2. Put the certificate in the project

1. You can directly drag the converted cer file into the project.

2. You can find the certificate you imported in the keychain, right-click to export the project, and then you can export the certificate of the .cer file.

2. Code preparation

<key>NSAppTransportSecurity</key>
  <dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
  </dict>

1.1 NSURLConnection settings support https.

In the 2015 iOS9 update, NSURLConnection was abandoned and replaced by NSURLSession, so it is not recommended that you continue to use this class to make network requests (there is also AFNetWorking version). However, considering some old programs, you cannot change it just by saying it or replace it just by saying it, so you still need to popularize it. If NSURLConnection is used, what do you need to do?

The code is as follows:

- (void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge{

  if( == NSURLAuthenticationMethodServerTrust) {
    // Tell the server that the client trusts the certificate    // Create a credential object    NSURLCredential *credntial = [NSURLCredential credentialForTrust:];
    // Tell the server to trust the certificate    [ useCredential:credntial forAuthenticationChallenge:challenge];
  }
}

You just need to simply add the proxy method as above to add support for https requests without affecting your original request.

1.2 NSURLSession settings support https.

Now the recommended use is NSURLSession to handle related network requests. If you use the system's own class, you can refer to the following code:

- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential * __nullable credential))completionHandler {

  // Determine whether it is a trust server certificate  if( == NSURLAuthenticationMethodServerTrust) {
    // Tell the server that the client trusts the certificate    // Create a credential object    NSURLCredential *credntial = [NSURLCredential credentialForTrust:];
    // Tell the server to trust the certificate through completionHandler    completionHandler(NSURLSessionAuthChallengeUseCredential,credntial);
  }
  NSLog(@"protectionSpace = %@",);
}

2. Use AFNetWorking to send network requests

AFNetworking is a likable network library for iOS and Mac OS X. It is built on NSURLConnection, NSOperation, and other familiar Foundation technologies. It has a good architecture, rich APIs, and modular construction, making it very easy to use.

2.1 AFNetWorking Version

Considering this version, we can also use the AFHTTPRequestOperationManager class to handle network requests. So what we need to do is set some parameters for this class so that it can support https requests. The code is as follows:

Support https (school verification certificate, no packet capture):

// 1. Initialize the singleton class  AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
   = AFSSLPinningModeCertificate;
  // 2. Set the certificate mode  NSString * cerPath = [[NSBundle mainBundle] pathForResource:@"xxx" ofType:@"cer"];
  NSData * cerData = [NSData dataWithContentsOfFile:cerPath];
   = [[NSArray alloc] initWithObjects:cerData, nil];
  // Whether the client trusts the illegal certificate   = YES;
  // Whether to verify the domain name in the certificate domain field  [ setValidatesDomainName:NO];

Support https (no verification certificate can be checked, you can catch the package and view it):

 // 1. Initialize the singleton class  AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
   = AFSSLPinningModeCertificate;
  // 2. Set non-calibration verification certificate mode   = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
   = YES;
  [ setValidatesDomainName:NO];

2.2 AFNetWorking Version

After Xcode 7.0, Apple abandoned the NSURLConnection method and used NSURLSession for data requests. As the AFN, which has the largest usage of the third-party library in the network request class, also updated the new version - AFN 3.0 version in a timely manner. The new version abandoned the AFHTTPRequestOperationManager encapsulated based on NSURLConnection and instead used the AFHTTPSessionManager encapsulated based on NSURLSession.

Support https (school verification certificate, no packet capture):

// 1. Initialization   AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
   = AFSSLPinningModeCertificate;
  // 2. Set the certificate mode  NSString * cerPath = [[NSBundle mainBundle] pathForResource:@"xxx" ofType:@"cer"];
  NSData * cerData = [NSData dataWithContentsOfFile:cerPath];
   = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate withPinnedCertificates:[[NSSet alloc] initWithObjects:cerData, nil]];
  // Whether the client trusts the illegal certificate   = YES;
  // Whether to verify the domain name in the certificate domain field  [ setValidatesDomainName:NO];

Support https (no verification certificate can be checked, you can catch the package and view it):

// 1. Initialization   AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
  // 2. Set non-calibration verification certificate mode   = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
   = YES;
  [ setValidatesDomainName:NO];

The configuration is completed here, I hope it will be helpful to you.