swift删除图像文件,throw文件不存在

时间:2017-02-04 17:08:06

标签: ios swift swift3 nsfilemanager

 let filename = getDocumentsDirectory().appendingPathComponent(upload.fileName)
               print("deleting")
            let fileNameToDelete = upload.fileName
            var filePath = ""          
            // Fine documents directory on device
            let dirs : [String] = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.allDomainsMask, true)          
            if dirs.count > 0 {
                let dir = dirs[0] //documents directory
                filePath = dir.appendingFormat("/" + fileNameToDelete)
                print("Local path = \(filePath)")      
            } else {
                print("Could not find local directory to store file")
                return
            }         
            print(filename)           
              print("deleting111111")
            do {
                let fileManager = FileManager.default  
                // Check if file exists
                print("filePath")
                print(filePath)
                 print("filePath")
                if fileManager.fileExists(atPath: filePath) {
                    // Delete file
                    try fileManager.removeItem(atPath: filePath)
                } else {
                    print("File does not exist")
                }            
            }
            catch let error as NSError {
                print("An error took place: \(error)")
            }}

这打印在下面。为什么删除不起作用?为什么上面的函数在文件中向我抛出它不存在

deleting
Local path = /var/mobile/Containers/Data/Application/C763B3ED-3371-47AB-8F61-4F086D01E430/Documents/profile-FFCEBEA9-2F8D-49E2-9A09-2BF87BD0B542--A9636AF4-350D-4D72-A4BD-E4F2B183F4BB.png
file:///var/mobile/Containers/Data/Application/C763B3ED-3371-47AB-8F61-4F086D01E430/Documents/profile-FFCEBEA9-2F8D-49E2-9A09-2BF87BD0B542--A9636AF4-350D-4D72-A4BD-E4F2B183F4BB.png
deleting111111
filePath
/var/mobile/Containers/Data/Application/C763B3ED-3371-47AB-8F61-4F086D01E430/Documents/profile-FFCEBEA9-2F8D-49E2-9A09-2BF87BD0B542--A9636AF4-350D-4D72-A4BD-E4F2B183F4BB.png
filePath
File does not exist

1 个答案:

答案 0 :(得分:0)

如果您通过写入使用

生成的文件名来创建文件
.right {
  margin-right: 2%;
  margin-left: auto;
  float: right;
}

...然后绝对至关重要,当删除文件的时候,你以完全相同的方式生成文件名。那不是你在做什么。

实际上,在您展示的代码中,您确实生成了一个名为<div class="social">的变量,其代码看起来很相似:

filename = getDocumentsDirectory().appendingPathComponent(nameOfImage+"‌​.PNG")

...但是你永远不会使用 filename做任何事情!因此,你不断伪装自己。您创建let filename = getDocumentsDirectory().appendingPathComponent(upload.fileName) ,打印filename,但不使用filename作为删除路径。您使用以不同方式获得的其他变量filename