How do you cancel a request in URLSession?
Essence
Every URLSessionTask has cancel(): the transfer is aborted and the completion closure or delegate receives URLError.cancelled (NSURLErrorCancelled, code −999). Cancellation is asynchronous — after cancel() the callback is still invoked, once, with that error. Download tasks have cancel(byProducingResumeData:) so the download can be resumed later.
The whole session is torn down with invalidateAndCancel() (cancel everything) or finishTasksAndInvalidate() (let current tasks finish); the session can't be used afterwards.
The rest of this answer, with code and interview follow-ups, is in the DevPrep app.
Read the full answer in DevPrep