0

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)
        session.dataTaskWithURL(url).resume()
    }

    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 NSURLSESSION and NSURLSessionDataTask

Ne AS
  • 1,490
  • 3
  • 26
  • 58

1 Answers1

1

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()
    newData.append(data)
    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.

Marcus
  • 2,153
  • 2
  • 13
  • 21