【问题标题】:Delete files in iOS directory using Swift使用 Swift 删除 iOS 目录中的文件
【发布时间】:2015-12-19 10:19:33
【问题描述】:

我在我的应用程序中下载了一些 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)")
    }
}

【问题讨论】:

  • 我怀疑您想考虑使用.CachesDirectory 而不是.DocumentDirectory 来保存和删除这些文件。
  • 我确实尝试将我的文件保存在那里,但没有成功
  • 那你一定要通读app backup best practicesQA1719
  • @TwoStraws 好点,很多关于 SO 的答案只使用文档目录,但他们不应该......

标签: ios swift


【解决方案1】:

此代码对我有用。我删除了所有缓存的图像。

private func test(){

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

    do {
        if let documentPath = documentsPath
        {
            let fileNames = try fileManager.contentsOfDirectoryAtPath("\(documentPath)")
            print("all files in cache: \(fileNames)")
            for fileName in fileNames {

                if (fileName.hasSuffix(".png"))
                {
                    let filePathName = "\(documentPath)/\(fileName)"
                    try fileManager.removeItemAtPath(filePathName)
                }
            }

            let files = try fileManager.contentsOfDirectoryAtPath("\(documentPath)")
            print("all files in cache after deleting images: \(files)")
        }

    } catch {
        print("Could not clear temp folder: \(error)")
    }
}

**** 快速更新 3 ****

        let fileManager = FileManager.default
        let documentsUrl =  FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first! as NSURL
        let documentsPath = documentsUrl.path

        do {
            if let documentPath = documentsPath
            {
                let fileNames = try fileManager.contentsOfDirectory(atPath: "\(documentPath)")
                print("all files in cache: \(fileNames)")
                for fileName in fileNames {

                    if (fileName.hasSuffix(".png"))
                    {
                        let filePathName = "\(documentPath)/\(fileName)"
                        try fileManager.removeItem(atPath: filePathName)
                    }
                }

                let files = try fileManager.contentsOfDirectory(atPath: "\(documentPath)")
                print("all files in cache after deleting images: \(files)")
            }

        } catch {
            print("Could not clear temp folder: \(error)")
        }

【讨论】:

  • 前 3 行 (Swift3) 非常棒,帮助我为我的录音机/播放器(即录音机)使用 CRUD!谢谢!
  • 完美匹配它的完美工作。还有共享文件夹。非常感谢
  • 对于任何寻找 Swift 4 的人:try? FileManager.default.removeItem(at: dest)
【解决方案2】:

我相信你的问题出在这一行:

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

您将contentsOfDirectoryAtPath()NSURL 结合使用。您可以选择路径字符串或 URL,而不是尝试将它们混合使用。为了抢占您可能提出的下一个问题,首选 URL。尝试使用contentsOfDirectoryAtURL()removeItemAtURL()

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

【讨论】:

  • 有没有办法删除“完整的CachesDirectory()”?
  • 不应删除文档和库/缓存。如果需要,可以添加和删除文件,但不要删除它们。注意:iOS 应根据需要为您清除 Llibrary/Caches。
  • 我理解对了吗 -> 不要删除 CachesDirectory() 中存储的文件,iOS 会自己“删除”它们?
  • 不,我说“如果需要,可以添加和删除它们”。您可以删除 Library/Caches 目录中的文件(而不是目录本身!),但如果您不想这样做,则不需要这样做。如果用户的设备空间不足,iOS 将始终清除缓存。这取决于您以及您希望应用程序如何运行 :)
  • 啊,好的,谢谢,那么我需要寻找一种方法来删除那里的“所有 PDF”:-)!
【解决方案3】:

斯威夫特 5:

查看FileManager.removeItem() method

// start with a file path, for example:
let fileUrl = FileManager.default.urls(
    for: .documentDirectory,
    in: .userDomainMask
).deletingPathExtension()
    .appendingPathComponent(
        "someDir/customFile.txt",
        isDirectory: false
    )

// check if file exists
// fileUrl.path converts file path object to String by stripping out `file://`
if FileManager.default.fileExists(atPath: fileUrl.path) {
    // delete file
    do {
        try FileManager.default.removeItem(atPath: fileUrl.path)
    } catch {
        print("Could not delete file, probably read-only filesystem")
    }
} 

【讨论】:

    猜你喜欢
    • 2012-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-09
    • 1970-01-01
    • 1970-01-01
    • 2019-04-09
    • 2013-07-31
    相关资源
    最近更新 更多