iosswiftnsurlsessiondownloadtask

Ambiguous reference to member 'downloadTask(with:completionHandler:)'


I'm trying to play audio from URL.

var downloadTask:URLSessionDownloadTask!
downloadTask = URLSession.shared.downloadTask(with: url, completionHandler: { (url, response, error) in
    playAudio(url: url)
})
downloadTask.resume()

but this gives me error pf ambiguous reference.

enter image description here


Solution

  • The compiler expects native URL, don't use NS... classes in Swift anyway if there is a native equivalent.

    And downloadTask is a non-optional constant. There is no reason to add a declaration line.

    And most likely you will get another error about requires explicit 'self.'

    func downloadTaskFromURL(url: URL) {
        let downloadTask = URLSession.shared.downloadTask(with: url, completionHandler: { (url, response, error) in
            self.playAudio(url: url)
        })
        downloadTask.resume()
    }
    

    Side note: According to the naming guidelines the method should be named func downloadTask(from url: URL).