Tupac
Tupac

Reputation: 83

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?

Upvotes: 4

Views: 3854

Answers (2)

Manish Verma
Manish Verma

Reputation: 539

You can also create a String extension like below:

extension String {

    func stringByAppendingPathComponent(path: String) -> String {

        let nsSt = self as NSString

        return nsSt.stringByAppendingPathComponent(path)
    }
}

And then use it like this:

let writePath = NSTemporaryDirectory().stringByAppendingPathComponent("<your string value>")

Hope this helps!!

Upvotes: 1

Bannings
Bannings

Reputation: 10479

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!

Upvotes: 0

Related Questions