Delete files in iOS directory using Swift

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

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)