使用Swift删除iOS目录中的文件

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

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

创建文件

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()函数删除项目,如下所示:

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)")
    }
}
我相信你的问题就在这条线上:
let filePaths = try fileManager.contentsOfDirectoryAtPath("\(documentsUrl)")

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

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

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...