Search code examples
iosswift

Swift Best Practices - how / when to check for internet connection and 404s when working with APIs


There are a wealth of resources for checking for a valid Internet connection with Swift (Reachability) and also ways to check the statusCode of the httpResponse when making an API call, but what is the "right" way to check and handle these errors (Internet not reachable, server 404) when dealing with an API heavy iOS app?

For example, when the app starts in the initial view (or AppDelegate I suppose) one can check for both and redirect to a "ServerProblemsViewController" that displays a message (or show an alert, though those can be dismissed). But what happens is someone is in the middle of using your app and the Internet drops or the server becomes unreachable? How would you handle this?

I am wondering if devs typically check for Reachability before EVERY API call and check the return status of EVERY API call, or somehow encapsulate that logic into a helper function?

How do experienced iOS devs deal with this situation?


Solution

  • I check for reachability on every call and then examine the response status code by type casting the NSURLResponse to an NSHTTPURLResponse (which has a statusCode property). And yes, my requests use the same base class to encapsulate all of the functionality--only creating derived classes when needed. You can use the reachability example code from Apple which has been ported to Swift and can be typically found on Github through the community. Simply reading through this repo will probably answer a lot of your questions about changes in reachability. Notifications FTW!: https://github.com/ashleymills/Reachability.swift