0

What am I doing wrong here? All I am trying to delete a given file, and all the documentation and examples I've seen make it seem like this should be working.

func deleteThisFile(fileToDelete: String) {
    let tempLocalDir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first
    do {
        let directoryContents = try FileManager.default.contentsOfDirectory(at: tempLocalDir!, includingPropertiesForKeys: nil, options: [])
        let tempList = directoryContents.filter{ $0.absoluteString.contains(fileToDelete) }

        //tried these things:
        try FileManager.removeItem(tempList.first) // Argument labels '(_:)' do not match any available overloads
       /*
        * try FileManager.removeItem(at: tempList.first!) // Ambiguous reference to member 'removeItem(atPath:)'
        * 
        * try FileManager.removeItem(atPath: (tempList.first?.absoluteString)!) // Ambiguous reference to member 'removeItem(atPath:)'
        */ 

    } catch let error as NSError {
        print(error.localizedDescription)
    }
}

The one that is not commented is what the FileManager.removeItem auto prompts for when I am typing it.

Any clarification on what is wrong would be great

Community
  • 1
  • 1
brw59
  • 502
  • 4
  • 19

1 Answers1

1

In Swift 3 you should use removeItem(at:) which is an instance method of NSFileManager. And you need to unwrap the optional before handing over to NSFileManager.

if let url = tempList.first {
    try FileManager.default.removeItem(at: url)
}
David Rodrigues
  • 844
  • 6
  • 6
  • why is '.default' needed? I mean, it seems to work, and I'm grateful, I just don't understand why the .default is needed – brw59 Oct 16 '16 at 07:50
  • Because you need an instance of `NSFileManager` or `FileManager` to call `removeItem(at:)`. Instead of using that singleton you can also instantiate a new `FileManager` but you always need an instance to invoke that method. – David Rodrigues Oct 16 '16 at 07:55