Understanding Swift URLSession.dataTask

 

Text

Description automatically generated

 

Paraphrase from Apple documentation:

The completion handler takes the following parameters: data, response, error.

 

I am confused with the “takes” here because when I am setting this up I just put in “data”, “response”,  and “error” and in the closure I am expecting those values to be populated by dataTask. Then I use them in the closure – specifically, I use the value of data to populate something else.

 

What is going on in “completionHandler”?

I think (from documentation): Creates a task that retrieves the contents of a URL based on the specified URL request object.

 

 

How does data get populated?

 

My best attempts to find dataTask

 

Text

Description automatically generated

Source: https://github.com/apple/swift/blob/a1a8dd7de24f62c20336d82e8be2bb8910fd454b/test/refactoring/ConvertAsync/convert_to_continuation.swift

 

I am not sure this is the URLSession code that is being used by my version of Xcode, but regardless, this doesn’t help. What is completionHandler doing in the screen shot above?

 

 

Nick Understanding and Confusion

dataTask accepts the url from “with: ___” and returns data, response, error that can be used in the trailing closure?

 

The function itself dataTask does stuff and returns data, response, and error. But why doesn’t dataTask just return data, response, error on the left hand side? Why do we need to make this closure do the “returning”? What benefit is that?