Llg Llg - 28 days ago 5x
iOS Question

Swift put dowloaded file into folder

I want to download a file and put it into a known path. I searched but I didn't understand how can I do that.

This is the code of the download:

func downloadFile(timeout: NSTimeInterval, completionHandler:(megabytesPerSecond: Double?, error: NSError?) -> ()) {
let url = NSURL(string: "http://insert.your.site.here/yourfile")!

startTime = CFAbsoluteTimeGetCurrent()
stopTime = startTime
bytesReceived = 0
speedTestCompletionHandler = completionHandler

let configuration = NSURLSessionConfiguration.ephemeralSessionConfiguration()
configuration.timeoutIntervalForResource = timeout
let session = NSURLSession(configuration: configuration, delegate: self, delegateQueue: nil)

func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) {
bytesReceived! += data.length
stopTime = CFAbsoluteTimeGetCurrent()

How can I put the received data into a folder?

NOTE: I use


The way I have implemented this in the past is to maintain a dictionary of dataTasks and their associated data objects (in case you are running several tasks at once) as a stored variable of the class that implements the task.

I'm not sure what syntax you're using, and I think it has changed between Swift 2 and 3.

In Swift 2, using NSURLSession(session:dataTask:didReceiveData) you can then do the following:

if let existingData = taskDictionary[dataTask] {
    let newData : NSMutableData = existingData.mutableCopy()
    taskDictionary[dataTask] = newData as NSData

In Swift3, Data is itself mutable (there is no corresponding mutable subclass), so I believe you can call append directly.

Either way, this gradually builds your data object. When the task completes, you then use the relevant delegate function to attempt to save the data via a try...catch clause using data.writeToFile or data.write (again depending on your version of swift).

Hope that helps.