"Add .resume()" Warning for URLSession Tasks

As Paul Hudson, a Swift Community Builder said on one of his tutorials:
"Notice the way we call resume() on the task straight away? That’s the gotcha – that’s the thing you’ll forget time and time again. Without it the request does nothing and you’ll be staring at a blank screen. But with it the request starts immediately, and control gets handed over to the system – it will automatically run in the background, and won’t be destroyed even after our method ends."

Why we can't just have a small warning when the user builds the code if he/she didn't use the .resume() on a URLSession task?
"If you want your task to run immediately, don't forget to add .resume() on the end of your task declaration."

Happy Coding!

IMO the important thing is to figure out how to disable the warning. Since if we realize later on that we don’t need to run the URLSession we painstakingly created, or if the said object escape the context, it is hard to statically proof that it’s been run.

2 Likes

Anyone writing more than one or two networking calls should be wrapping them in some sort of convenience API to make request creation easier and take care of issues like this. In addition to the difficulty of detecting this issue, it's perfectly legitimate to create a task and not call resume right away, or at all.

2 Likes

Maybe you could get this rule added to SwiftLint. Linters support more optional rules or stylistic rules like this.

1 Like
Terms of Service

Privacy Policy

Cookie Policy