Able to write/read file but unable to delete file SWIFT

限于喜欢 提交于 2019-12-04 01:40:58

问题


I store an .jpg image i the iOS documents directory. I can write files and read files but when it comes to deleting them it says that there is no such file but that cannot be because I can read it with the same url.

Reading:

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!)

Deleting:

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)")
            }

It throws:

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:


Your fullPath variable is a (optional) URL. To convert that to a file path string, use the .path property, not string interpolation:

fileManager.removeItem(atPath: fullPath!.path)

Or better, use the URL directly without converting it to a path:

fileManager.removeItem(at: fullPath!)

(And get rid of the forced unwrapping in favor of option binding ... :-)



来源:https://stackoverflow.com/questions/39659939/able-to-write-read-file-but-unable-to-delete-file-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!