NSURLConnection ignore unverified certificate error when sending a synchronise request

时间:2023-03-08 16:58:17

Private API, use with caution.

As we all know, it's easy to ignore the unverified certificate error when we are sending an asynchronise request. We can use the NSURLDelegate method to ignore that error, all we need to do is to override the following method:

- (void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
    [challenge.senderuseCredential:[NSURLCredentialcredentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge];
}

And there's also a way to ignore the unverified certificate error when we are sending a synchronise request:

Before the @implementation of your http client, you could add the following code:

@interface NSURLRequest (IgnoreSSL)
+ (BOOL)allowsAnyHTTPSCertificateForHost:(NSString*)host;
@end @implementation NSURLRequest (IgnoreSSL)
+ (BOOL)allowsAnyHTTPSCertificateForHost:(NSString*)host
{
return YES;
}
@end

This replacement method gets automatically called and you can decide based on the host to allow any certificates or not. Alternatively you can always return YES regardless of the host parameter to ignore all invalid certificates.

Then you would use the following code to get data from the server with an unverified certificate:

NSData* data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];