What happens to the current tasks present in the session when we do reset(completionHandler:) on UrlSession. Also if it cancels the current tasks then how do we wait for the completion of the current tasks before calling reset(completionHandler:)
1 Answers
When you call URLSession reset
, all running tasks continue to run.
A common use case to use reset
is, where you want to clear all data associated to the signed-in user for example - a "sign-out" feature. Requests resumed before calling reset
may use the old URL Credential store, but yet they may use the new URL cache when the response completes. This is certainly NOT what you want.
So, a more robust way to accomplish this is as follows:
- prevent new tasks to be started (avoiding any data race issues)
- clear all data associated to the old "session environment" - which may include access tokens and user data etc.
- cancel all running tasks (asynchronously - fire & forget), then
- call
reset
, then - enable resuming tasks.
New tasks will use the new "session environment", previously resumed tasks will complete with a cancellation error.
The first bullet point is probably the most complex one, since you need to ensure that you even do not create requests using data associated to the old session environment. That may be solved using a network layer that has a feature where incoming high level "API requests" will be queued, and that queue can be suspended and resumed.

- 18,174
- 3
- 45
- 67