URLSessionTaskDelegate
で通信の完了時に URLRequest
を取り出したいときあるじゃないですか。
そのとき、毎回忘れるけど、URLSession
から URLRequest
は取り出せない。取り出せるのは URLSessionTask
から。
// MARK: - URLSessionTaskDelegate
func urlSession(_ session: URLSession,
task: URLSessionTask,
didCompleteWithError error: Error?) {
print(task.currentRequest)
}
Appleのドキュメントを読むと
https://developer.apple.com/documentation/foundation/urlsessiontask/1411649-currentrequest
2つのリクエストが取得できる。
- var currentRequest: URLRequest?
- The URL request object currently being handled by the task.
- var originalRequest: URLRequest?
- The original request object passed when the task was created.
リダイレクトされた時を考えて、originalRequest
も用意されている。つまりリダイレクトされると currentRequest
は original とは違ったものになっているようだ。