import Cocoa
class Requester: NSObject, URLSessionDelegate, URLSessionDownloadDelegate {
var response: URLResponse!
var session: URLSession!
var downloadTask: URLSessionDownloadTask!
var downloadData: NSData!
let opQueue = OperationQueue()
func operation() {
print("download function started")
let config = URLSessionConfiguration.default // Session configuration
self.session = URLSession(configuration: config, delegate: self, delegateQueue: self.opQueue) // load configuration into session
let url = URL(string: "http://www.radiologic.fr/dicom/test.dcm")
downloadTask = session?.downloadTask(with: url!)
// task are not started by default
downloadTask.resume()
} // end func
// The delegate is informed that the session has been invalidated by calling finishTasksAndInvalidate() or
// invalidateAndCancel().
func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?) {
if let err = error {
print("Error: \(err.localizedDescription)")
} else {
print("The session has been terminated.")
}
} // end func
// The delegate is periodically informed about the dwnload's progress
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
let progress = Float(totalBytesWritten) / Float(totalBytesExpectedToWrite)
print(progress)
} // end func
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
let folder = NSHomeDirectory()
let filename = "test.dcm"
let filepath = folder + "/" + filename
let fileManager = FileManager.default
if fileManager.fileExists(atPath: filepath) == true {
do {
try fileManager.removeItem(atPath: filepath)
}
catch let error as NSError {
print("Ooops! Something went wrong: \(error)")
} // end do
} // end if
let fileURL = URL(fileURLWithPath: filepath)
do {
try fileManager.moveItem(at: location, to: fileURL)
print("File succesfully loaded")
print(fileURL)
self.session?.finishTasksAndInvalidate()
} catch {
print(error)
}
} // end func
} // end class