iOS https请求第一步从服务器下载证书

来源:互联网 发布:finally java 编辑:程序博客网 时间:2024/06/17 11:08
+ (void)InitCertWithBlock:(void (^)(BOOL))block{    NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];    NSLog(@"--->%@", docPath);    NSString *certDirPath = [docPath stringByAppendingPathComponent:@"Cert"];    NSString *certTxtPath = [certDirPath stringByAppendingPathComponent:@"CertTxt.txt"];        NSFileManager *fileManager = [NSFileManager defaultManager];    [fileManager createDirectoryAtPath:certDirPath withIntermediateDirectories:YES attributes:nil error:nil];        NSURLSession *session = [NSURLSession sharedSession];    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:DWGETCER]];    request.HTTPMethod = @"POST";    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {        if (!error) {            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];            if ([dic[@"errorCode"] intValue] == 0) {                NSString *certFileURL = dic[@"data"];                if ([fileManager fileExistsAtPath:certTxtPath] && [fileManager fileExistsAtPath:[certDirPath stringByAppendingPathComponent:@"bemm.cer"]]) {                    NSString *localCertFileURL = [NSString stringWithContentsOfFile:certTxtPath encoding:NSUTF8StringEncoding error:nil];                    if ([certFileURL isEqualToString:localCertFileURL]) {                        block(YES);                        return ;                    }                }                //下载证书                NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:certFileURL]];                NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {                    if (!error) {                        [data writeToFile:[certDirPath stringByAppendingPathComponent:@"bemm.cer"] atomically:YES];                        [certFileURL writeToFile:certTxtPath atomically:YES encoding:NSUTF8StringEncoding error:nil];                        block(YES);                        return ;                    } else {                        block(NO);                        return ;                    }                }];                [task resume];            } else {                block(NO);                return ;            }        } else {            block(NO);            return;        }    }];    [task resume];}

0 0
原创粉丝点击