当前位置:  开发笔记 > IOS > 正文

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

如何解决《使用Swift删除iOS目录中的文件》经验,为你挑选了2个好方法。

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

Saleh Masum.. 46

这段代码适合我.我删除了所有缓存的图像.

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)")
    }
}

****更新swift 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)")
        }


TwoStraws.. 19

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

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

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

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



1> Saleh Masum..:

这段代码适合我.我删除了所有缓存的图像.

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)")
    }
}

****更新swift 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)")
        }



2> TwoStraws..:

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

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

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

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

推荐阅读
小妖694_807
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有