我使用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下载隔离到我刚刚创建的临时文件夹中,我只是附加了一个path组件:
tempPath = NSTemporaryDirectory().stringByAppendingPathComponent(NSProcessInfo().globallyUniqueString).stringByAppendingPathComponent("thisShouldBeTheNameOfTheFile")在本例中,下载不工作,没有创建任何内容,也没有调用函数downloadDidFinish。
临时目录是受保护的,所以我不能在里面创建一个新文件夹吗?我怎么才能解决这个问题?
发布于 2015-06-01 14:56:37
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)
}希望这对你有帮助!
发布于 2016-04-19 06:54:22
您还可以创建如下所示的字符串扩展:
extension String {
func stringByAppendingPathComponent(path: String) -> String {
let nsSt = self as NSString
return nsSt.stringByAppendingPathComponent(path)
}
}然后像这样使用它:
let writePath = NSTemporaryDirectory().stringByAppendingPathComponent("<your string value>")希望这能帮上忙!
https://stackoverflow.com/questions/30575757
复制相似问题