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

Checking response Time of API in iOS using Swift 3?

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

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

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

这是我的一个 API(我在 ApiManager class 中单独 class 编写了所有 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 "}
    }
}

不需要 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。然后您可以在几个地方(包括每个地方)测量执行时间:网络请求完成后(在完成处理程序的开头)和每个 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 "}
    }
}

Alamofire 仅提供请求的时间轴 response.timeline.totalDuration 它提供从请求开始到响应序列化完成的时间间隔(以秒为单位)。

response.timeline.totalDuration 是正确答案。