Monday, January 30, 2023

NSURLSession Connection Leak

Jeff Johnson:

What it doesn’t tell you is that if you don’t invalidate the session (via finishTasksAndInvalidate or invalidateAndCancel), then the internet connection created by the session remains open until the app terminates, even after the delegate method URLSession:task:didCompleteWithError: has been called, and even after the app’s code no longer has a strong reference to the session. It’s more than just a potential memory leak.


The NSURLSession API seems peculiar, because you would expect URLSession:task:didCompleteWithError: to be, you know, the end. Shouldn’t you be able to freely (pun intended) dispose of the connection at that point? The reality, however, is that you need to invalidate every used session.

1 Comment RSS · Twitter · Mastodon

Even if you don’t invalidate the session, the connection will eventually close, but only after some timeout period has elapsed.

Leave a Comment