Search code examples
swiftnsurlsessionnsurlsessiondatatask

Swift Get URLSessionDataTask start time / current operation time


I have a URLSessionDataTask instance and I would like to know when the operation started (a Date object) so I can calculate how much time has elapsed.

I've found URLSessionTaskTransactionMetrics in Apple's documentation (https://developer.apple.com/documentation/foundation/urlsessiontasktransactionmetrics#declarations) but this does not show how to get the transactionMetrics property, unless I'm missing something obvious.


Solution

  • Assuming you have already set your view controller as the URLSessionTaskDelegate, you just need to override url session didFinishCollecting metrics method, iterate over the metrics transactionMetrics and get its fetchStartDate:

    func urlSession(_ session: URLSession, task: URLSessionTask, didFinishCollecting metrics: URLSessionTaskMetrics) {
        for metric in metrics.transactionMetrics {    
            print(task.response?.url ?? "", metric.fetchStartDate?.description(with: .current) ?? "")
        }
    }