Checking response Time of API in iOS using Swift 3?

response.timeline.totalDuration is the correct answer.


Alamofire provides the timeline of request just response.timeline.totalDuration it provides time interval in seconds from the time the request started to the time response serialization completed.


Using Alamofire, you can use response.timeline.totalDuration, otherwise see the solution below that doesn't require any 3rd party libraries.

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