能够写入/读取文件但无法删除文件SWIFT

时间:2016-09-23 11:42:32

标签: swift directory delete-file nsfilemanager

我在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
)}

1 个答案:

答案 0 :(得分:5)

您的fullPath变量是(可选)URL。要将其转换为文件路径字符串,请使用.path属性,而不是字符串插值:

fileManager.removeItem(atPath: fullPath!.path)

或者更好的是,直接使用URL而不将其转换为路径:

fileManager.removeItem(at: fullPath!)

(摆脱强制解包,转而选择绑定...: - )