[英]Checking response Time of API in iOS using Swift 3?
我知道測試 API 的響應時間基本上是由服務器端或后端完成的,但是當我正在為一個應用程序工作時,我還需要從 iOS 端檢查 api 響應時間。
我怎樣才能做到這一點? 我讀了幾個鏈接,它說使用計時器開始和計時器結束來執行此操作,然后通過endTime - startTime找到響應時間,但這似乎並不方便。
我想使用 Xcode (即使 XCTest 在那里)。
這是我的 API 之一(我在 ApiManager ZA2F2ED4F8EBC2CBBD4C21 中的單獨 class 中編寫了所有 web 服務消耗方法):
登錄VC :
//Call Webservice
let apiManager = ApiManager()
apiManager.delegate = self
apiManager.getUserInfoAPI()
接口管理器:
func getUserInfoAPI() {
//Header
let headers = [
"Accept" : "application/json",
"Content-Type" : "application/json",
]
//Call Web API using Alamofire library
AlamoFireSharedManagerInit()
Alamofire.request(HCConstants.URL, method: .post, parameters: nil, encoding: JSONEncoding.default, headers: headers).responseJSON { response in
do{
//Checking For Error
if let error = response.result.error {
//Stop AcitivityIndicator
self.hideHud()
//Call failure delegate method
//print(error)
self.delegate?.APIFailureResponse(HCConstants.EXCEPTION_MESSAGES.SERVICE_FAILURE)
return
}
//Store Response
let responseValue = try JSONSerialization.jsonObject(with: response.data!, options: JSONSerialization.ReadingOptions()) as! Dictionary<String, AnyObject>
print(responseValue)
//Save token
if let mEmail = responseValue[HCConstants.Email] as? String {
UserDefaults.standard.setValue(mEmail, forKey: HCConstants. mEmail)
}
//Stop AcitivityIndicator
self.hideHud()
//Check Success Flag
if let _ = responseValue["info"] as? String {
//Call success delegate method
self.delegate?.apiSuccessResponse(responseValue)
}
else {
//Failure message
self.delegate?.APIFailureResponse(responseValue["message"] as? String ?? HCConstants.EXCEPTION_MESSAGES.SERVICE_FAILURE)
}
} catch {print("Exception is there "}
}
}
不需要Timer
,只需使用Date
對象即可。 您應該創建一個Date
對象,表示啟動API請求時的當前日期,並在API請求的completionHandler中,使用Date().timeIntervalSince(date: startDate)
來計算傳遞的秒數。
假設您有一個函數用於將閉包作為完成處理程序返回的請求,這就是您可以測量其執行時間的方法:
let startDate = Date()
callMyAPI(completion: { returnValue in
let executionTime = Date().timeIntervalSince(date: startDate)
})
Xcode本身沒有任何分析工具,但你可以在Instruments中使用Time Profiler,但是,我不確定是否能為異步函數提供正確的結果。
特定功能的解決方案:您可以在函數調用后立即保存startDate
。 然后,您可以在多個位置(包括每個位置)測量執行時間:在網絡請求完成后(在完成處理程序的開頭)和調用委托方法之前的每個if statement
。
func getUserInfoAPI() {
let startDate = Date()
...
Alamofire.request(HCConstants.URL, method: .post, parameters: nil, encoding: JSONEncoding.default, headers: headers).responseJSON { response in
//calculate the time here if you only care about the time taken for the network request
let requestExecutionTime = Date().timeIntervalSince(date: startDate)
do{
if let error = response.result.error {
self.hideHud()
let executionTimeWithError = Date().timeIntervalSince(date: startDate)
self.delegate?.APIFailureResponse(HCConstants.EXCEPTION_MESSAGES.SERVICE_FAILURE)
return
}
//Store Response
...
//Check Success Flag
if let _ = responseValue["info"] as? String {
//Call success delegate method
let executionTimeWithSuccess = Date().timeIntervalSince(date: startDate)
self.delegate?.apiSuccessResponse(responseValue)
}
else {
//Failure message
let executionTimeWithFailure = Date().timeIntervalSince(date: startDate)
self.delegate?.APIFailureResponse(responseValue["message"] as? String ?? HCConstants.EXCEPTION_MESSAGES.SERVICE_FAILURE)
}
} catch {print("Exception is there "}
}
}
response.timeline.totalDuration
是正確的答案。
Alamofire提供請求的時間線,只是response.timeline.totalDuration,它提供從請求開始到完成時間響應序列化的時間間隔(以秒為單位)。
response.metrics?.taskInterval.duration
是更新的答案。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.