Tupac Tupac - 6 months ago 70
Swift Question

Can't append path component to the temporary directory path in Swift

I'm using NSURLDownload to download a zip file in a Mac temporary folder. Here's the code :

func function () {
var request:NSURLRequest = NSURLRequest(URL: NSURL(string: self.downloadLink.stringValue)!)
var download:NSURLDownload = NSURLDownload(request: request, delegate: self)

func download(download: NSURLDownload, decideDestinationWithSuggestedFilename filename: String) {
tempPath = NSTemporaryDirectory().stringByAppendingPathComponent(NSProcessInfo().globallyUniqueString)
download.setDestination(tempPath.stringByAppendingPathExtension("zip")!, allowOverwrite: false)

This works, but I'm trying to isolate my zip download into the temporary folder I just created by appending a path component :

tempPath = NSTemporaryDirectory().stringByAppendingPathComponent(NSProcessInfo().globallyUniqueString).stringByAppendingPathComponent("thisShouldBeTheNameOfTheFile")

In this case, the download doesn't work, nothing is created and the function downloadDidFinish is not called.

Is the temporary directory protected so I can't create a new folder inside? How can I fix this?


The download.setDestination method, that does not automatically create a directory if the directory does not exist.

Try this:

func download(download: NSURLDownload, decideDestinationWithSuggestedFilename filename: String) {
    let tempPathDirectory = NSTemporaryDirectory().stringByAppendingPathComponent(NSProcessInfo().globallyUniqueString)

    let fileManager = NSFileManager.defaultManager()
    if fileManager.fileExistsAtPath(tempPathDirectory) == false {
        fileManager.createDirectoryAtPath(tempPathDirectory, withIntermediateDirectories: true, attributes: nil, error: nil)

    let tempPath = tempPathDirectory.stringByAppendingPathComponent("thisShouldBeTheNameOfTheFile")

    download.setDestination(tempPath.stringByAppendingPathExtension("zip")!, allowOverwrite: false)

Hope this have helped you!