【问题标题】:Checking response Time of API in iOS using Swift 3?使用 Swift 3 检查 iOS 中 API 的响应时间?
【发布时间】:2017-08-24 12:45:11
【问题描述】:

我知道测试 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 "}
    }
}

【问题讨论】:

    标签: ios performance swift3 response


    【解决方案1】:

    不需要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 "}
        }
    }
    

    【讨论】:

    • 由于您的问题中没有代码,我无法给出确切的答案。但是,您始终可以在要开始测量之前在代码中声明startDate,并在网络请求本身的completionHandler 中计算executionTime
    • 我认为 OP 想要使用 XCTest 来执行此操作?这不是您在 XCTest 中测量异步时序的方式。
    • @matt 我不能代表 OP,但由于答案已被接受,我想情况并非如此。此外,从唯一提到XCTest 的句子(“我想使用Xcode(即使XCTest 在那里)。”)我的理解是OP 不想使用XCTest at全部。
    • 我也不明白 OP 的意思,所以我们同意这一点。 :)
    • 谢谢,我得到了 5.28927099704742 是响应。好吧,我并不完全坚持使用 XCTest,这个解决方案也适用于我,谢谢
    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

      response.timeline.totalDuration 是正确答案。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-05-03
        • 1970-01-01
        • 2019-04-25
        • 1970-01-01
        • 2016-04-29
        • 2017-02-17
        • 1970-01-01
        相关资源
        最近更新 更多