Delete files in iOS directory using Swift

I believe your problem is on this line:

let filePaths = try fileManager.contentsOfDirectoryAtPath("\(documentsUrl)")

You're using contentsOfDirectoryAtPath() with something that is an NSURL. You choose either path strings or URLs, not try to mix them both. To pre-empty your possible next question, URLs are preferred. Try using contentsOfDirectoryAtURL() and removeItemAtURL().

Another curious thing you should look at once you resolve the above: why are you using NSTemporaryDirectory() for the file path when you try to delete? You're reading the document directory and should use that.


Swift 5:

Check out the FileManager.removeItem() method

// start with a file path, for example:
let fileUrl = FileManager.default.urls(
    for: .documentDirectory,
    in: .userDomainMask
).deletingPathExtension()
    .appendingPathComponent(
        "someDir/customFile.txt",
        isDirectory: false
    )

// check if file exists
// fileUrl.path converts file path object to String by stripping out `file://`
if FileManager.default.fileExists(atPath: fileUrl.path) {
    // delete file
    do {
        try FileManager.default.removeItem(atPath: fileUrl.path)
    } catch {
        print("Could not delete file, probably read-only filesystem")
    }
} 

This code works for me. I removed all the images that were cached.

private func test(){

    let fileManager = NSFileManager.defaultManager()
    let documentsUrl =  NSFileManager.defaultManager().URLsForDirectory(.CachesDirectory, inDomains: .UserDomainMask).first! as NSURL
    let documentsPath = documentsUrl.path

    do {
        if let documentPath = documentsPath
        {
            let fileNames = try fileManager.contentsOfDirectoryAtPath("\(documentPath)")
            print("all files in cache: \(fileNames)")
            for fileName in fileNames {

                if (fileName.hasSuffix(".png"))
                {
                    let filePathName = "\(documentPath)/\(fileName)"
                    try fileManager.removeItemAtPath(filePathName)
                }
            }

            let files = try fileManager.contentsOfDirectoryAtPath("\(documentPath)")
            print("all files in cache after deleting images: \(files)")
        }

    } catch {
        print("Could not clear temp folder: \(error)")
    }
}

**** Update swift 3 ****

        let fileManager = FileManager.default
        let documentsUrl =  FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first! as NSURL
        let documentsPath = documentsUrl.path

        do {
            if let documentPath = documentsPath
            {
                let fileNames = try fileManager.contentsOfDirectory(atPath: "\(documentPath)")
                print("all files in cache: \(fileNames)")
                for fileName in fileNames {

                    if (fileName.hasSuffix(".png"))
                    {
                        let filePathName = "\(documentPath)/\(fileName)"
                        try fileManager.removeItem(atPath: filePathName)
                    }
                }

                let files = try fileManager.contentsOfDirectory(atPath: "\(documentPath)")
                print("all files in cache after deleting images: \(files)")
            }

        } catch {
            print("Could not clear temp folder: \(error)")
        }

Tags:

Ios

Swift