Delete files in iOS directory using Swift

前端 未结 2 725
有刺的猬
有刺的猬 2021-01-31 03:15

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

For some reason it does not work:

Creating the file:

l         


        
2条回答
  •  眼角桃花
    2021-01-31 03:42

    This code works for me. I removed all the images that were cached.

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

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

提交回复
热议问题