gpt4 book ai didi

ios - 使用 Swift 3 检查 iOS 中 API 的响应时间?

转载 作者:可可西里 更新时间:2023-11-01 04:12:10 26 4
gpt4 key购买 nike

我知道测试 API 的响应时间基本上是由服务器端或后端完成的,但由于我正在为一个应用程序工作,我还需要从 iOS 端检查 API 响应时间。

我该怎么做?我读了几个链接,其中说使用定时器启动和定时器结束来执行此操作,然后通过 endTime - startTime 找到响应时间,但这似乎并不方便。

我想使用 Xcode(即使有 XCTest)。

这是我的一个 API(我在 ApiManager 类的单独类中编写了所有 Web 服务使用方法):

登录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 "}
}
}

最佳答案

使用 Alamofire,您可以使用 response.timeline.totalDuration,否则请参阅下面不需要任何第 3 方库的解决方案。

不需要 Timer,您可以只使用 Date 对象。您应该在开始 API 请求时创建一个代表当前日期的 Date 对象,并在 API 请求的 completionHandler 中使用 Date().timeIntervalSince(date: startDate) 来计算经过的秒数。

假设您的请求有一个函数返回一个闭包作为完成处理程序,这就是您测量其执行时间的方法:

let startDate = Date()
callMyAPI(completion: { returnValue in
let executionTime = Date().timeIntervalSince(date: startDate)
})

Xcode 本身没有任何分析工具,但您可以在 Instruments 中使用 Time Profiler,但是,我不确定是否会为异步函数提供正确的结果。

针对您的特定功能的解决方案:您可以在函数调用后立即保存 startDate。然后,您可以在几个地方(包括每个地方)测量执行时间:在网络请求完成后(在完成处理程序的开头)和在调用委托(delegate)方法之前的每个 if 语句 中。

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 "}
}
}

关于ios - 使用 Swift 3 检查 iOS 中 API 的响应时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45862023/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com