我正在使用NSURLDownload在Mac临时文件夹中下载zip文件。这是代码:
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)
}
这样可行,但我试图通过附加路径组件将我的zip下载隔离到我刚刚创建的临时文件夹中:
tempPath = NSTemporaryDirectory().stringByAppendingPathComponent(NSProcessInfo().globallyUniqueString).stringByAppendingPathComponent("thisShouldBeTheNameOfTheFile")
在这种情况下,下载不起作用,不会创建任何内容,也不会调用函数downloadDidFinish。
临时目录是否受到保护,因此我无法在其中创建新文件夹?我怎样才能解决这个问题?
答案 0 :(得分:1)
您还可以创建如下字符串扩展名:
extension String {
func stringByAppendingPathComponent(path: String) -> String {
let nsSt = self as NSString
return nsSt.stringByAppendingPathComponent(path)
}
}
然后像这样使用它:
let writePath = NSTemporaryDirectory().stringByAppendingPathComponent("<your string value>")
希望这会有所帮助!!
答案 1 :(得分:0)
download.setDestination
方法,如果目录不存在,则不会自动创建目录。
试试这个:
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)
}
希望这对你有帮助!