Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
823 views
in Technique[技术] by (71.8m points)

performance - 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.

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.

I want to use Xcode (even if XCTest is there).

Here is my one of API ( i wrote all web service consume method in separate class in ApiManager class ) :

LoginVC :

//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 "}
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There's no need for a Timer, you can just use Date objects. 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.

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.

Solution for your specific function: you can save the startDate right after the function call. 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.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...