Search code examples
swiftnsurlsessiondownloadtask

Using downloadtask with url


I'm trying to use downloadTaskWithURL() but upgrading it to the latest version: downloadTask and I'm trying to run this code snippet but it won't compile.

Here's what I have done so far:

let downloadTask: URLSessionDownloadTask = URLSession.shared.downloadTask(with url: endpointURL, completionHandler: { (url: URL!, response: URLResponse!, error: Error!)

    if (error == nil) {
        //some code 
    }
})

downloadTask.resume()

What am I doing wrong?


Solution

  • You have several errors: your function signature is wrong (url is only used inside the function body, when calling it, the name of the input parameter is with) and you missed in after specifying the closure variables. Find the code which compiles without an issue below:

    let downloadTask = URLSession.shared.downloadTask(with: endpointURL, completionHandler: { url, response, error in
        if error == nil {
            //some code 
        }
    })
    
    downloadTask.resume()