問題描述:使用Alamofire + Moya請求框架,突然出現第一次請求會非常非常慢的情況,在3s - 10s的時候才會返回數據
初始以為Moya或者Alamofire出現了問題,於是更新到最新版本,並查看github的issue,並沒有其他人出現這種情況,后跟后端進行聯調,發現后台安全證書替換為Let's Encrypt,在替換回去后恢復正常
在測試過程中,一直想要知道Moya通過Alamofire發起請求的過程中每一步的時間是多少,具體是卡在哪個步驟導致的請求過慢,后來發現Alamofire封裝的請求包含的有一個屬性metrics,這個東西是在Response中進行的返回,可以打印查看具體時間指標。
然而Moya並沒有將這個東西進行返回,所以也就不能在Moya的Response里面進行查看打印,於是尋找Moya調用Alamofire回調的地方,最終在Moya+Alamofire.swift文件里面找到了回調方法,在這里打印,即可獲取到請求的過程耗費時間。
internal func response(callbackQueue: DispatchQueue?, completionHandler: @escaping RequestableCompletion) -> Self {
if let callbackQueue = callbackQueue {
return response(queue: callbackQueue) { handler in
completionHandler(handler.response, handler.request, handler.data, handler.error)
}
} else {
return response { handler in
print(handler.metrics)
completionHandler(handler.response, handler.request, handler.data, handler.error)
}
}
}
在該方法打印metrics即可
打印如下:
(Fetch Start) 2020-06-22 07:20:56 +0000
(Domain Lookup Start) 2020-06-22 07:20:56 +0000
(Domain Lookup End) 2020-06-22 07:20:56 +0000
(Connect Start) 2020-06-22 07:20:56 +0000
(Secure Connection Start) 2020-06-22 07:20:56 +0000
(Secure Connection End) 2020-06-22 07:20:56 +0000
(Connect End) 2020-06-22 07:20:56 +0000
(Request Start) 2020-06-22 07:20:56 +0000
(Request End) 2020-06-22 07:20:56 +0000
(Response Start) 2020-06-22 07:20:56 +0000
(Response End) 2020-06-22 07:20:56 +0000
(Protocol Name) h2
(Proxy Connection) NO
(Reused Connection) NO
(Fetch Type) Network Load
(Request Header Bytes) 246
(Request Body Transfer Bytes) 0
(Request Body Bytes) 0
(Response Header Bytes) 157
(Response Body Transfer Bytes) 560
(Response Body Bytes) 2433
(Local Address) ***.**.***.**
(Local Port) 55732
(Remote Address) **.***.***.**
(Remote Port) 443
(TLS Protocol Version) 0x0303
(TLS Cipher Suite) 0xC030
(Cellular) NO
(Expensive) NO
(Constrained) NO
(Multipath) NO
即可看出請求的具體耗時地方在哪