[英]Checking response Time of API in iOS using Swift 3?
I know to test the response time of API is basically done by Server or Backend side, but as i am working for one application, i need to check api response time from iOS End also.我知道测试 API 的响应时间基本上是由服务器端或后端完成的,但是当我正在为一个应用程序工作时,我还需要从 iOS 端检查 api 响应时间。
How can i do this?我怎样才能做到这一点? i read few links where it says to do this using timer start and timer end and then find the response time by endTime - startTime but this seems not handy.
我读了几个链接,它说使用计时器开始和计时器结束来执行此操作,然后通过endTime - startTime找到响应时间,但这似乎并不方便。
I want to use Xcode (even if XCTest is there).我想使用 Xcode (即使 XCTest 在那里)。
Here is my one of API ( i wrote all web service consume method in separate class in ApiManager class ):这是我的 API 之一(我在 ApiManager ZA2F2ED4F8EBC2CBBD4C21 中的单独 class 中编写了所有 web 服务消耗方法):
LoginVC :登录VC :
//Call Webservice
let apiManager = ApiManager()
apiManager.delegate = self
apiManager.getUserInfoAPI()
ApiManager :接口管理器:
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 "}
}
}
There's no need for a Timer
, you can just use Date
objects. 不需要
Timer
,只需使用Date
对象即可。 You should create a Date
object representing the current date at the time of starting your API request and in the completionHandler of your API request, use Date().timeIntervalSince(date: startDate)
to calculate the number of seconds that passed. 您应该创建一个
Date
对象,表示启动API请求时的当前日期,并在API请求的completionHandler中,使用Date().timeIntervalSince(date: startDate)
来计算传递的秒数。
Assuming you have a function for your requests that is returning a closure as a completion handler, this is how you can measure its execution time: 假设您有一个函数用于将闭包作为完成处理程序返回的请求,这就是您可以测量其执行时间的方法:
let startDate = Date()
callMyAPI(completion: { returnValue in
let executionTime = Date().timeIntervalSince(date: startDate)
})
Xcode itself doesn't have any profiling tools, but you can use Time Profiler in Instruments, however, I am not sure if would give the correct results for asynchronous functions. Xcode本身没有任何分析工具,但你可以在Instruments中使用Time Profiler,但是,我不确定是否能为异步函数提供正确的结果。
Solution for your specific function: you can save the startDate
right after the function call. 特定功能的解决方案:您可以在函数调用后立即保存
startDate
。 Then you can measure the execution time in several places (included each): right after the network request finishes (at the beginning of the completion handler) and in each if statement
right before your delegate method is called. 然后,您可以在多个位置(包括每个位置)测量执行时间:在网络请求完成后(在完成处理程序的开头)和调用委托方法之前的每个
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
is the updated answer. response.metrics?.taskInterval.duration
是更新的答案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.