使用Swift删除iOS目录中的文件 [英] Delete files in iOS directory using Swift

查看:552
本文介绍了使用Swift删除iOS目录中的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的应用程序中下载了一些PDF文件,并希望在关闭应用程序时删除这些文件。

I downloaded some PDF files in my app and want to delete these on closing the application.

由于某种原因它不起作用:

For some reason it does not work:

创建文件:

let reference = "test.pdf"    
let RequestURL = "http://xx/_PROJEKTE/xx\(self.reference)"
let ChartURL = NSURL(string: RequestURL)

//download file
let documentsUrl =  NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first! as NSURL
let destinationUrl = documentsUrl.URLByAppendingPathComponent(ChartURL!.lastPathComponent!)
if NSFileManager().fileExistsAtPath(destinationUrl.path!) {
    print("The file already exists at path")
} else {
    //  if the file doesn't exist
    //  just download the data from your url
    if let ChartDataFromUrl = NSData(contentsOfURL: ChartURL!){
        // after downloading your data you need to save it to your destination url
        if ChartDataFromUrl.writeToURL(destinationUrl, atomically: true) {
            print("file saved")
            print(destinationUrl)
        } else {
            print("error saving file")
        }
    }
}

然后我想调用 test()函数删除项目,如下所示:

Then I want to call the test() function to remove the items, like this:

func test(){

    let fileManager = NSFileManager.defaultManager()
    let documentsUrl =  NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first! as NSURL

    do {
        let filePaths = try fileManager.contentsOfDirectoryAtPath("\(documentsUrl)")
        for filePath in filePaths {
            try fileManager.removeItemAtPath(NSTemporaryDirectory() + filePath)
        }
    } catch {
        print("Could not clear temp folder: \(error)")
    }
}


推荐答案

我相信你的问题就在这条线上:

I believe your problem is on this line:

let filePaths = try fileManager.contentsOfDirectoryAtPath("\(documentsUrl)")

您正在使用 contentsOfDirectoryAtPath(),其中包含 NSURL 。您可以选择路径字符串或URL,而不是尝试将它们混合使用。要预先清空您可能的下一个问题,首选网址。尝试使用 contentsOfDirectoryAtURL() removeItemAtURL()

You're using contentsOfDirectoryAtPath() with something that is an NSURL. You choose either path strings or URLs, not try to mix them both. To pre-empty your possible next question, URLs are preferred. Try using contentsOfDirectoryAtURL() and removeItemAtURL().

解决上述问题后,您应该注意另一个奇怪的事情:当您尝试删除文件路径时,为什么要使用 NSTemporaryDirectory()?您正在阅读文档目录,应该使用它。

Another curious thing you should look at once you resolve the above: why are you using NSTemporaryDirectory() for the file path when you try to delete? You're reading the document directory and should use that.

这篇关于使用Swift删除iOS目录中的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆