Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
)}
like image 289
Lenny1357 Avatar asked Sep 23 '16 11:09

Lenny1357


1 Answers

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 ... :-)

like image 169
Martin R Avatar answered Sep 22 '22 23:09

Martin R