DevPrep

All topics › Networking & APIs

How do you cancel a request in URLSession?

Middle PRO

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

Practice this before your interview

DevPrep turns these answers into one-minute challenges: what does this code print, find the bug, mock interviews. One challenge a day.

Get DevPrep on the App Store