jjatie
jjatie

Reputation: 5332

URLSession instance method `downloadTask` error

I've updated the Advanced NSOperations sample app to Swift 3. The only remaining build error is on this snippet of code from the DownloadEarthquakesOperation class.

    let url = URL(string: "http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/2.5_month.geojson")!

    let task = URLSession.shared.downloadTask(with: url) { (url, response, error) in
        self.downloadFinished(url, response: response, error: error)
    }

The error reads:

Cannot invoke 'downloadTask' with an argument list of type '(with: URL, (URL?, URLResponse?, Error?) -> Void)'

Expected an argument list of type '(with: URL, completionHandler: @escaping (URL?, URLResponse?, Error?) -> Void)'

This error doesn't make any sense to me as the @escaping attribute shouldn't affect the call site. Any thoughts?

Upvotes: 1

Views: 1115

Answers (2)

Rob
Rob

Reputation: 437682

One line closures can often cause problems because the compiler is trying to infer the return type for the closure from whatever that one line in the closure returns. Theoretically it should be able to infer the correct type (because downloadFinished returns Void), but it looks like there are so many issues during the initial conversion of AdvancedNSOperations that it's just getting confused. You can silence that warning by adding an explicit return statement:

let url = URL(string: "http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/2.5_month.geojson")!

let task = URLSession.shared.downloadTask(with: url) { url, response, error in
    self.downloadFinished(url, response: response, error: error)
    return
}

Frankly, once I finished the conversion (fixing all of the other issues), I was able to go back and remove that return statement and it was no longer a problem.

Upvotes: 1

javimuu
javimuu

Reputation: 1859

Try it in Swift 3:

let url = URL(string: "http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/2.5_month.geojson")!

URLSession.shared.dataTask(with: url, completionHandler: { (data, response, error) in
    if error != nil {
        print(error!)
        return
    }
    // dosomething here
    print(data)

}).resume()

Hope it help!

Upvotes: 0

Related Questions