0

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.

Evan Kaminsky
  • 695
  • 10
  • 23

1 Answers1

2

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) ?? "")
    }
}
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
  • I'm trying to set the delegate of my URLSession to a delegate conforming object, e.g. URLSession.shared.delegate = Object, but I'm getting a 'delegate' is a get-only property warning. Am I setting the right delegate? It doesn't seem that URLSessionTasks have a delegate property either. – Evan Kaminsky Apr 04 '19 at 20:14
  • 1
    I'm forever in your debt, Leo. – Evan Kaminsky Apr 04 '19 at 21:07