Devran's and djunod's solutions are working as long as your application is in the foreground. If you switch to another application during the download, it fails. My file sizes are around 10 MB and it takes sometime to download. So I need my download function works even when the app goes into background.
Please note that I switched ON the "Background Modes / Background Fetch" at "Capabilities".
Since completionhandler was not supported the solution is not encapsulated. Sorry about that.
--Swift 2.3--
import Foundation
class Downloader : NSObject, NSURLSessionDownloadDelegate
{
var url : NSURL?
// will be used to do whatever is needed once download is complete
var yourOwnObject : NSObject?
init(yourOwnObject : NSObject)
{
self.yourOwnObject = yourOwnObject
}
//is called once the download is complete
func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didFinishDownloadingToURL location: NSURL)
{
//copy downloaded data to your documents directory with same names as source file
let documentsUrl = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first
let destinationUrl = documentsUrl!.URLByAppendingPathComponent(url!.lastPathComponent!)
let dataFromURL = NSData(contentsOfURL: location)
dataFromURL?.writeToURL(destinationUrl, atomically: true)
//now it is time to do what is needed to be done after the download
yourOwnObject!.callWhatIsNeeded()
}
//this is to track progress
func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64)
{
}
// if there is an error during download this will be called
func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?)
{
if(error != nil)
{
//handle the error
print("Download completed with error: \(error!.localizedDescription)");
}
}
//method to be called to download
func download(url: NSURL)
{
self.url = url
//download identifier can be customized. I used the "ulr.absoluteString"
let sessionConfig = NSURLSessionConfiguration.backgroundSessionConfigurationWithIdentifier(url.absoluteString)
let session = NSURLSession(configuration: sessionConfig, delegate: self, delegateQueue: nil)
let task = session.downloadTaskWithURL(url)
task.resume()
}
}
And here is how to call in --Swift 2.3--
let url = NSURL(string: "http://company.com/file.txt")
Downloader(yourOwnObject).download(url!)
--Swift 3--
class Downloader : NSObject, URLSessionDownloadDelegate {
var url : URL?
// will be used to do whatever is needed once download is complete
var yourOwnObject : NSObject?
init(_ yourOwnObject : NSObject)
{
self.yourOwnObject = yourOwnObject
}
//is called once the download is complete
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL)
{
//copy downloaded data to your documents directory with same names as source file
let documentsUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first
let destinationUrl = documentsUrl!.appendingPathComponent(url!.lastPathComponent)
let dataFromURL = NSData(contentsOf: location)
dataFromURL?.write(to: destinationUrl, atomically: true)
//now it is time to do what is needed to be done after the download
yourOwnObject!.callWhatIsNeeded()
}
//this is to track progress
private func URLSession(session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64)
{
}
// if there is an error during download this will be called
func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?)
{
if(error != nil)
{
//handle the error
print("Download completed with error: \(error!.localizedDescription)");
}
}
//method to be called to download
func download(url: URL)
{
self.url = url
//download identifier can be customized. I used the "ulr.absoluteString"
let sessionConfig = URLSessionConfiguration.background(withIdentifier: url.absoluteString)
let session = Foundation.URLSession(configuration: sessionConfig, delegate: self, delegateQueue: nil)
let task = session.downloadTask(with: url)
task.resume()
}}
And here is how to call in --Swift 3--
let url = URL(string: "http://company.com/file.txt")
Downloader(yourOwnObject).download(url!)