首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >无法在Swift中将path组件附加到临时目录路径

无法在Swift中将path组件附加到临时目录路径
EN

Stack Overflow用户
提问于 2015-06-01 14:10:35
回答 2查看 3.5K关注 0票数 4

我使用NSURLDownload在Mac临时文件夹中下载一个zip文件。下面是代码:

代码语言:javascript
复制
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组件:

代码语言:javascript
复制
tempPath = NSTemporaryDirectory().stringByAppendingPathComponent(NSProcessInfo().globallyUniqueString).stringByAppendingPathComponent("thisShouldBeTheNameOfTheFile")

在本例中,下载不工作,没有创建任何内容,也没有调用函数downloadDidFinish。

临时目录是受保护的,所以我不能在里面创建一个新文件夹吗?我怎么才能解决这个问题?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-06-01 14:56:37

download.setDestination方法,该方法在目录不存在时不会自动创建目录。

试试这个:

代码语言:javascript
复制
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)
}

希望这对你有帮助!

票数 0
EN

Stack Overflow用户

发布于 2016-04-19 06:54:22

您还可以创建如下所示的字符串扩展:

代码语言:javascript
复制
extension String {

    func stringByAppendingPathComponent(path: String) -> String {

        let nsSt = self as NSString

        return nsSt.stringByAppendingPathComponent(path)
    }
}

然后像这样使用它:

代码语言:javascript
复制
let writePath = NSTemporaryDirectory().stringByAppendingPathComponent("<your string value>")

希望这能帮上忙!

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30575757

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档