快速删除图像文件,抛出文件不存在
Posted
技术标签:
【中文标题】快速删除图像文件,抛出文件不存在【英文标题】:swift delete image file, throw file does not exist 【发布时间】:2017-02-04 17:08:06 【问题描述】: 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
【问题讨论】:
文件是否存在? 它应该,因为我用下面的这个保存它.. func getDocumentsDirectory() -> URL let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask) let documentsDirectory = paths[0] return documentsDirectory 让 filename = getDocumentsDirectory().appendingPathComponent(nameOfImage+".PNG") 试试? image_data?.write(to: filename) 我认为这里打印了一个本地文件路径 print("Local path = (filePath)") 正确。它没有给我找不到本地目录来存储文件 【参考方案1】:如果您通过写入生成的文件名来创建文件
filename = getDocumentsDirectory().appendingPathComponent(nameOfImage+".PNG")
...那么绝对至关重要,当需要删除文件时,以完全相同的方式生成文件名。那不是你正在做的事情。
确实,在您显示的代码中,您确实生成了一个名为filename
的变量,代码看起来很相似:
let filename = getDocumentsDirectory().appendingPathComponent(upload.fileName)
...但是你永远不会使用 filename
做任何事情!因此,您一直在伪装自己。创建filename
,打印filename
,但不使用filename
作为删除路径。您使用其他一些变量,filePath
,以不同的方式获得。
【讨论】:
另外,dir.appendingFormat("/" + fileNameToDelete)
是一种使用文件路径的糟糕方式。
在我看来,在整个过程中使用文件 URL 并完全使用 URL 方法会好得多。使用此方法获取文档目录:developer.apple.com/reference/foundation/filemanager/… 并完全从那里工作。字符串文件路径是魔鬼的工作;这就是为什么首选 URL。以上是关于快速删除图像文件,抛出文件不存在的主要内容,如果未能解决你的问题,请参考以下文章
ffmpeg 在尝试用图像制作幻灯片时抛出“输出文件 #0 不包含任何流”
不小心删除了支持文件夹下的 info.plist 文件:怎么办?
Laravel 4.2 抛出 NotReadableException “不支持的图像类型。GD 驱动程序只能解码 JPG、PNG、GIF 或 WebP 文件。”