能够写入/读取文件但无法删除文件SWIFT
问题描述:
我在iOS文档目录中存储.jpg图像。我可以编写文件和读取文件,但是在删除它时说它没有这样的文件,但这不能,因为我可以用相同的URL读取它。能够写入/读取文件但无法删除文件SWIFT
阅读:
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
)}
答
你fullPath
变量是一个(可选)URL
。要转换的文件路径字符串,请使用.path
属性,而不是字符串插值:
fileManager.removeItem(atPath: fullPath!.path)
或者更好,使用URL的情况下直接将其转换为路径:
fileManager.removeItem(at: fullPath!)
(,摆脱强制展开以支持选项绑定... :-)
+0
你知道什么目标c eq uivalent会是? – Matt
print fullPath pls –
file:/// var/mobile/Containers/Data/Application/269ADA58-6B09-4844-9FAA-AC2407C1D991/Documents/image_496251232 .806566.jpg – Lenny1357