Search code examples
iosswiftdownloadnsdatansurlsession

Copy tmp file fast


I was wondering, if there is a different and faster solution to the following problem. I am downloading a file with NSURLSession. By default (I guess?) the downloaded file is stored in the tmp folder. Then I need to copy this file to the cache folder. At the moment I am using this code for my approach (in the didFinishDownloading function)

if let fileData = NSData(contentsOfURL: sourceUrl) {
        fileData.writeToURL(destinationURL, atomically: true)   // true
        print(destinationURL.path!)
        }

However, as my file is pretty large, this takes a while. Is there a different option on copying this file to the cache folder? Or is it possible to download a file directly to the Cache folder using the NSURLSession?


Solution

  • Instead of copying the file you can simply move it to the desired location:

    do {
        try NSFileManager.defaultManager().moveItemAtURL(sourceURL, toURL: destinationURL)
    } catch let err as NSError {
        print(err.localizedDescription)
    }
    

    This would be much faster because only directory entries in the file system are modified, but no data is actually copied.

    Swift 3 update:

    do {
        try FileManager.default.moveItem(at: sourceURL, to: destinationURL)
    } catch {
        print(error.localizedDescription)
    }