Search code examples
swiftcocoansurlsessiondownloadtask

Downloading File with NSURLSessionDownloadTask


I need to download a file with my desktop application. First, I've created a simple iOS project for downloading a video file, referring to this web site. It works. And I want to do pretty much the same thing for macOS.

class ViewController: NSViewController, URLSessionDownloadDelegate {
    var downloadTask: URLSessionDownloadTask!
    var backgroundSession: URLSession!
    var assetFile = String() // file in application's sandboxed folder

    override func viewDidLoad() {
        super.viewDidLoad()

        let backgroundSessionConfiguration = URLSessionConfiguration.background(withIdentifier: "backgroundSession")
        backgroundSession = Foundation.URLSession(configuration: backgroundSessionConfiguration, delegate: self, delegateQueue: OperationQueue.main)
    }

    override func viewDidAppear() {
        super.viewDidAppear()
        let url = URL(string: "https://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4")!
        downloadTask = backgroundSession.downloadTask(with: url)
        downloadTask.resume()
    }

    func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
        let fileManager = FileManager()
        do {
            let assetURL = URL(fileURLWithPath: assetFile)
            try fileManager.moveItem(at: location, to: assetURL)
        } catch {
            print("An error occurred while moving file to destination url")
        }
    }

    func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {

    }

    func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
        downloadTask = nil
        if (error != nil) {
            print(error!.localizedDescription) // <<< error here?
        } else {
            print("The task finished transferring data successfully")
        }
    }
}

If I run it, I get a log message that says "unknown error." I wonder what I'm doing wrong? I do have App Transport Security Setting > Allow Allow Arbitrary Loads set to YES. Thanks.


Solution

  • As your app is sandboxed make sure that Outgoing Connections are enabled in the sandbox capabilities.

    enter image description here

    The ATS settings have no effect for a HTTPS connection