NSURLSession https證書設置

1.設置代理

NSURLSession *sesson = [NSURLSession sessionWithConfiguration:
[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc]init]];

2.在代理方法中實現對證書的操作

方法一:這是在開發(fā)者足夠信任后端的安全的情況下做的紊遵,比如調個接口账千,這樣做的結果就是忽略證書的驗證威恼,直接信任坤检。

- (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable))completionHandler{     
if([challenge.protectionSpace.authenticationMethodisEqualToString:NSURLAuthenticationMethodServerTrust]){//服務器信任證書                  
NSURLCredential *credential = [NSURLCredentialcredentialForTrust:challenge.protectionSpace.serverTrust];//服務器信任證書         
if(completionHandler)         
completionHandler(NSURLSessionAuthChallengeUseCredential,credential);    
 } 
} 

方法二:可以把證書加到工程中,然后https訪問時在代理方法中進行證書的驗證

- (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler: 
(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable))completionHandler{
    SecTrustRef servertrust = challenge.protectionSpace.serverTrust;
    SecCertificateRef certi= SecTrustGetCertificateAtIndex(servertrust, 0);
    NSData *certidata = CFBridgingRelease(CFBridgingRetain(CFBridgingRelease(SecCertificateCopyData(certi))));
    NSString *path = [[NSBundle mainBundle] pathForResource:@"https" ofType:@"cer"];
    NSData *localCertiData = [NSData dataWithContentsOfFile:path];
    if ([certidata isEqualToData:localCertiData]) {
        NSURLCredential *credential = [[NSURLCredential alloc] initWithTrust:servertrust];         
 [challenge.sender useCredential:credential forAuthenticationChallenge:challenge];
        completionHandler(NSURLSessionAuthChallengeUseCredential, credential);
        NSLog(@"服務端證書認證通過"); 
    }else {
        completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, nil);
        NSLog(@"服務端認證失敗");
        
    }
}
-(void)URLSession:(NSURLSession *)session
didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge
completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable))completionHandler {

    NSURLSessionAuthChallengeDisposition disposition = NSURLSessionAuthChallengePerformDefaultHandling;
    NSURLCredential * credential = nil;

    if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
        if (self.sslChallengeMode == XKHTTPClientSSLChallengeModeNone) {
            // 使用服務端的證書對服務端進行校驗,那肯定是怎樣都通過,自簽名證書都能通過
            disposition = NSURLSessionAuthChallengeUseCredential;
            credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
        } else if(self.sslChallengeMode == XKHTTPClientSSLChallengeModeSimple) {
            SecTrustRef serverTrust = challenge.protectionSpace.serverTrust;
            NSArray * policies = @[ (__bridge_transfer id)SecPolicyCreateBasicX509() ];
            SecTrustSetPolicies(serverTrust, (__bridge CFArrayRef)policies);
            SecTrustResultType result;
            if(SecTrustEvaluate(serverTrust, &result) == errSecSuccess &&
               (result == kSecTrustResultUnspecified || result == kSecTrustResultProceed)) {
                // x509認證,不會對服務端證書中的域名和請求的域名進行一致性校驗
                // 校驗成功,則直接傳遞服務端證書來對服務端鑒權進行校驗,即:怎樣都會成功
                disposition = NSURLSessionAuthChallengeUseCredential;
                credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
            } else {
                // x509校驗失敗,則走默認的校驗邏輯
                disposition = NSURLSessionAuthChallengePerformDefaultHandling;
            }
        } else {
            // 默認校驗邏輯:ATS,即對證書錨點删铃、證書鏈進行校驗且會對證書中的域名和請求的域名的一致性進行校驗
            disposition = NSURLSessionAuthChallengePerformDefaultHandling;
        }
    } else {
        disposition = NSURLSessionAuthChallengePerformDefaultHandling;
    }

    if (completionHandler) {
        completionHandler(disposition, credential);
    }
}

在了解了網絡請求的流程之后桦山,我們可以先測試一下自己項目網絡請求耗時分布攒射。
通過監(jiān)聽NSURLSession的didFinishCollectingMetrics回調方法,了解各種耗時操作

- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didFinishCollectingMetrics:(NSURLSessionTaskMetrics *)metrics API_AVAILABLE(macosx(10.12), ios(10.0), watchos(3.0), tvos(10.0))

{
    if (@available(iOS 10.0, *)) {
        for (NSURLSessionTaskTransactionMetrics *sessionMetric in metrics.transactionMetrics) {
            NSInteger dom = ([sessionMetric.domainLookupEndDate timeIntervalSince1970] - [sessionMetric.domainLookupStartDate timeIntervalSince1970]) * 1000 ;
            NSInteger sec = ([sessionMetric.secureConnectionEndDate timeIntervalSince1970] - [sessionMetric.secureConnectionStartDate timeIntervalSince1970]) * 1000;
            NSInteger con = ([sessionMetric.connectEndDate timeIntervalSince1970] - [sessionMetric.connectStartDate timeIntervalSince1970]) * 1000;
            NSInteger req = ([sessionMetric.requestEndDate timeIntervalSince1970] - [sessionMetric.requestStartDate timeIntervalSince1970]) * 1000;
            NSInteger res = ([sessionMetric.responseEndDate timeIntervalSince1970] - [sessionMetric.responseStartDate timeIntervalSince1970]) * 1000;
            NSInteger tot = ([sessionMetric.responseEndDate timeIntervalSince1970] - [sessionMetric.fetchStartDate timeIntervalSince1970]) * 1000;

            NSString *locip = @"";
            NSString *remip = @"";

            if (@available(iOS 13.0, *)) {
                locip = [NSString stringWithFormat:@"%@", sessionMetric.localAddress];
                remip = [NSString stringWithFormat:@"%@", sessionMetric.remoteAddress];
            }

            NSLog(@"metric path:%@ 總耗時:%ldms, 域名解析:%ldms, 連接耗時:%ldms(包括TLS:%ldms), 請求:%ldms, 回調:%ldms l:%@ r:%@",sessionMetric.request.URL.lastPathComponent,tot,dom,con,sec,req,res, locip, remip);
        }
    }
} 

此時就可以進行對應的網絡情況優(yōu)化恒水。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
  • 序言:七十年代末会放,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子钉凌,更是在濱河造成了極大的恐慌咧最,老刑警劉巖,帶你破解...
    沈念sama閱讀 221,548評論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現場離奇詭異矢沿,居然都是意外死亡滥搭,警方通過查閱死者的電腦和手機,發(fā)現死者居然都...
    沈念sama閱讀 94,497評論 3 399
  • 文/潘曉璐 我一進店門捣鲸,熙熙樓的掌柜王于貴愁眉苦臉地迎上來瑟匆,“玉大人,你說我怎么就攤上這事栽惶〕盍铮” “怎么了?”我有些...
    開封第一講書人閱讀 167,990評論 0 360
  • 文/不壞的土叔 我叫張陵外厂,是天一觀的道長冕象。 經常有香客問我,道長汁蝶,這世上最難降的妖魔是什么渐扮? 我笑而不...
    開封第一講書人閱讀 59,618評論 1 296
  • 正文 為了忘掉前任,我火速辦了婚禮掖棉,結果婚禮上墓律,老公的妹妹穿的比我還像新娘。我一直安慰自己啊片,他們只是感情好只锻,可當我...
    茶點故事閱讀 68,618評論 6 397
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著紫谷,像睡著了一般齐饮。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上笤昨,一...
    開封第一講書人閱讀 52,246評論 1 308
  • 那天祖驱,我揣著相機與錄音,去河邊找鬼瞒窒。 笑死捺僻,一個胖子當著我的面吹牛,可吹牛的內容都是我干的崇裁。 我是一名探鬼主播匕坯,決...
    沈念sama閱讀 40,819評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼拔稳!你這毒婦竟也來了葛峻?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 39,725評論 0 276
  • 序言:老撾萬榮一對情侶失蹤巴比,失蹤者是張志新(化名)和其女友劉穎术奖,沒想到半個月后礁遵,有當地人在樹林里發(fā)現了一具尸體,經...
    沈念sama閱讀 46,268評論 1 320
  • 正文 獨居荒郊野嶺守林人離奇死亡采记,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 38,356評論 3 340
  • 正文 我和宋清朗相戀三年佣耐,在試婚紗的時候發(fā)現自己被綠了。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片唧龄。...
    茶點故事閱讀 40,488評論 1 352
  • 序言:一個原本活蹦亂跳的男人離奇死亡兼砖,死狀恐怖,靈堂內的尸體忽然破棺而出既棺,到底是詐尸還是另有隱情掖鱼,我是刑警寧澤,帶...
    沈念sama閱讀 36,181評論 5 350
  • 正文 年R本政府宣布援制,位于F島的核電站,受9級特大地震影響芍瑞,放射性物質發(fā)生泄漏晨仑。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,862評論 3 333
  • 文/蒙蒙 一拆檬、第九天 我趴在偏房一處隱蔽的房頂上張望洪己。 院中可真熱鬧,春花似錦竟贯、人聲如沸答捕。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,331評論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽拱镐。三九已至,卻和暖如春持际,著一層夾襖步出監(jiān)牢的瞬間沃琅,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,445評論 1 272
  • 我被黑心中介騙來泰國打工蜘欲, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留益眉,地道東北人。 一個月前我還...
    沈念sama閱讀 48,897評論 3 376
  • 正文 我出身青樓姥份,卻偏偏與公主長得像郭脂,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子澈歉,可洞房花燭夜當晚...
    茶點故事閱讀 45,500評論 2 359

推薦閱讀更多精彩內容