Evan Kaminsky
Evan Kaminsky

Reputation: 715

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.

Upvotes: 0

Views: 1781

Answers (1)

Leo Dabus
Leo Dabus

Reputation: 236548

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

Upvotes: 2

Related Questions