Len*_*357 3 directory nsfilemanager delete-file swift
我在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!)
Run Code Online (Sandbox Code Playgroud)
删除:
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)")
}
Run Code Online (Sandbox Code Playgroud)
它抛出:
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
)}
Run Code Online (Sandbox Code Playgroud)
你的fullPath变量是(可选)URL.要将其转换为文件路径字符串,请使用.path属性,而不是字符串插值:
fileManager.removeItem(atPath: fullPath!.path)
Run Code Online (Sandbox Code Playgroud)
或者更好的是,直接使用URL而不将其转换为路径:
fileManager.removeItem(at: fullPath!)
Run Code Online (Sandbox Code Playgroud)
(并摆脱强制解包,支持选项绑定...... :-)
| 归档时间: |
|
| 查看次数: |
2341 次 |
| 最近记录: |