我在iOS文档目录中存储了.jpg图像。我可以写文件和读取文件,但是当它要删除它们时它说没有这样的文件但是不能因为我可以用相同的URL读取它。
读:
let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
let path = NSURL(fileURLWithPath: paths[0] as String)
let fullPath = path.appendingPathComponent(info["pi"] as! String)
let data = NSData(contentsOf: fullPath!)
删除:
let fileManager = FileManager.default
fileManager.delegate = self
let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
let path = NSURL(fileURLWithPath: paths[0] as String)
let fullPath = path.appendingPathComponent(info["pi"] as! String)
do {
try fileManager.removeItem(atPath: "\(fullPath!)")
} catch {
print("\(error)")
}
它抛出:
Error Domain=NSCocoaErrorDomain Code=4 "“image_496251232.806566.jpg” couldn’t be removed." UserInfo={NSUnderlyingError=0x1758eb40 {Error Domain=NSPOSIXErrorDomain Code=2 "No such file or directory"}, NSFilePath=file:///var/mobile/Containers/Data/Application/269ADA58-6B09-4844-9FAA-AC2407C1D991/Documents/image_496251232.806566.jpg, NSUserStringVariant=(
Remove
)}
答案 0 :(得分:5)
您的fullPath
变量是(可选)URL
。要将其转换为文件路径字符串,请使用.path
属性,而不是字符串插值:
fileManager.removeItem(atPath: fullPath!.path)
或者更好的是,直接使用URL而不将其转换为路径:
fileManager.removeItem(at: fullPath!)
(摆脱强制解包,转而选择绑定...: - )