Good Code Procedure: URLSession.dataTask

Table of Contents

In our lesson today, we were provided some template code to assist us in our guided project during our lecture. Included was some netcode for URLSession. I just wanted to take a moment and share my appreciation for its clarity and thoroughness. I’ve used dataTask a couple times in my own projects and never really had any good examples at how to structure my results, and I thought this was a particularly good implementation:

//1
func fetchAThing(completion: @escaping (<aThing>?, Error?) -> Void) {
    URLSession.shared.dataTask(with: "https://url.com/either/passed/in/or/global") { (data, _, error) in

        //2
        if let error = error {
            completion(nil, error)
            return
        }

        //3
        guard let data = data else {
            completion(nil, NSError())
            return
        }

        //4
        do {
            let thingDecoded = try JSONDecoder().decode(<aThing>.self, from: data)
            completion(thingDecoded, nil)
        } catch {
            completion(nil, error)
            return
        }
    }.resume()
}

Breakdown

Breaking it down, here’s why it’s so great:

  1. Wherever you decide to put this code, giving it a completion handler to pass its data into is great. That makes it super modular to fit many different situations.
  2. Check for a communication error. If there is an error, we know something went south and can then just exit early, calling our completion handler and letting it know there was an error.
  3. This step confirms the data is actually valid. If something were to happen where the data was bad, we again call our completion handler and give it an error.
  4. Finally, we attempt to decode our data into our Codable objects, again with an error fallback. In most cases (hopefully), this should succeed and give our completion handler our good data! But we still have the error to fall back on.

I hope this helps clean up some of the strangeness (or understanding) that networking code can cause!

1 thought on “Good Code Procedure: URLSession.dataTask”

Leave a Reply

Your email address will not be published. Required fields are marked *