iOS忽略SSL证书错误的API请求

在请求API时,如果服务器的API为https://218.37.82.243/test/query (这个地址是我随便写的,主要说明服务器地址没有绑定域名),那个么当发送网络请求时,肯定会返回失败。

因为服务器地址没有绑定域名,在iOS9之后http请求都改为了https,没有绑定域名的服务器无法将SSL证书发送到client端,此时需要忽略掉这个错误。

下面就是代码,网络请求的结果通过SessionRequestBlock这个Block返回,返回两个参数isSucceed和result。isSucceed用于标示网络请求是否成功,result存放网络请求的结果。

在SessionRequest.h文件中

#import 

typedef void (^SessionRequestBlock)(BOOL isSucceed, id result);

@interface SessionRequest : NSObject

- (void)urlSessionWithReuqest:(NSURLRequest *)request Block:(SessionRequestBlock)block;

@end

在SessionRequest.m文件中

#import "SessionRequest.h"
@implementation SessionRequest

- (void)urlSessionWithReuqest:(NSURLRequest *)request Block:(SessionRequestBlock)block {
    NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        NSLog(@"%@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);
        NSMutableDictionary *responseData = [NSMutableDictionary dictionary];
        if (data == nil) {
            //无返回数据
            if (block) {
                block(NO,@"无返回数据");
            }
        }else {
            NSError *jsonError = nil;
            id jsonDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&jsonError];
            
            if (jsonError) {
                //无法解析
                if (block) {
                    block(NO,@"无法解析");
                }
            }else {
                if ([jsonDic isKindOfClass:[NSArray class]]) {
                    [responseData setValue:jsonDic forKey:@"data"];
                }else if ([jsonDic isKindOfClass:[NSDictionary class]]) {
                    responseData = jsonDic;
                }
                
                if (block) {
                    block(YES,responseData);
                }
            }
        }
    }];
    [dataTask resume];
}


#pragma mark - NSURLSessionDataDelegate
//只要请求的地址是HTTPS的, 就会调用这个代理方法
//challenge:质询
//NSURLAuthenticationMethodServerTrust:服务器信任
-(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable))completionHandler
{
    NSLog(@"%@",challenge.protectionSpace);
    
    if (![challenge.protectionSpace.authenticationMethod isEqualToString:@"NSURLAuthenticationMethodServerTrust"]) return;
    /*
     NSURLSessionAuthChallengeUseCredential 使用证书
     NSURLSessionAuthChallengePerformDefaultHandling  忽略证书 默认的做法
     NSURLSessionAuthChallengeCancelAuthenticationChallenge 取消请求,忽略证书
     NSURLSessionAuthChallengeRejectProtectionSpace 拒绝,忽略证书
     */
    
    NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
    
    completionHandler(NSURLSessionAuthChallengeUseCredential,credential);
}
@end```

你可能感兴趣的:(iOS忽略SSL证书错误的API请求)