I tried something new.
This week, I decided to rethink my newsletter intro. It's often hard for me to develop a valuable topic, and I want to make this newsletter as valuable as possible.
Therefore, I decided to handle one of the questions asked weekly.
I reached out on Twitter and got several great questions from which I'm handling one today:
How many eggs do your chickens lay?
Alright, of course, I'm not picking this one! (The answer is 3 btw). Instead:
What’s your opinion on the best practice to retry a failing network request?
This question by Vincent Pradeilles received a lot of likes which proves it's an interesting topic! And of course, it is: almost every app performs requests, and what do we do if that network request fails?
First of all; There are a few points I want to clear out:
----
You don't want to retry each failing network request
Quoted from WWDC Session
Advances in Networking:
"Avoid retrying URLSessionTasks due to lack of network connectivity."
Only retry up to 3 times max.
It's not worth retrying more than 3 times. There's probably something wrong, which is why the request failed.
Try to handle the error instead.
What is the reason your request fails? It might be an authentication error or something else. It's likely better to handle this error if chances are high you'll receive the same response again.
----
So, if you really want to do retrying, my personal recommendation would be to use
Alamofire's built-in solution. I know many of you prefer to use URLSession, but in my opinion, retrying is one of those reasons to adopt a popular framework like Alamofire. It's well-documented and explains how you can implement a retrying mechanism taking the above points into account. Sure, you shouldn't easily add a 3rd party dependency, but if it saves you from writing a lot of custom logic around networking, it might be worth it!
Hopefully, that was a useful intro! I feel like some of the questions are too big for a blog post but big enough to handle here. Next week on Monday, I'll reach out to you on
Twitter again for some questions!
Enjoy this week's SwiftLee Weekly!