Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FileManager.default.removeItem not removing file [duplicate]

I'm trying to remove a file from the documents directory using FileManager.default.removeItem but is not deleting the file on the simulator. Here is my code:

if let dir = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first {
            do{
                let path = dir.appendingPathComponent(file).absoluteString
                do{
                    try FileManager.default.removeItem(atPath:path)
                }catch{
                    print(error)
                }
            }
        }

But I always fails. Any of you knows why it fails?

like image 378
user2924482 Avatar asked Apr 27 '17 07:04

user2924482


2 Answers

You can write like this:

var filemanager = FileManager.default
let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory,.userDomainMask,true)[0] as NSString
let destinationPath = documentsPath.appendingPathComponent("Filename.jpg")
try! filemanager.removeItem(atPath: destinationPath)
like image 133
Pragnesh Vitthani Avatar answered Nov 10 '22 22:11

Pragnesh Vitthani


absoluteString is the wrong API, the correct property for the file:// scheme is path.

The best solution is to use the URL related API

let fileURL = dir.appendingPathComponent(file)

...

try FileManager.default.removeItem(at: fileURL)
like image 40
vadian Avatar answered Nov 10 '22 21:11

vadian