删除文档目录中的多个文件

时间:2016-01-22 22:08:17

标签: swift nsfilemanager

我正在尝试创建一个函数,我可以使用给定的文件扩展名删除文档目录中的多个文件。

到目前为止,我有以下功能,但我可以在较旧的时候完成删除已创建的文件吗?

static func searchFilesDocumentsFolder(Extension: String) {

        let documentsUrl =  NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first!

        do {
            let directoryUrls = try  NSFileManager.defaultManager().contentsOfDirectoryAtURL(documentsUrl, includingPropertiesForKeys: nil, options: NSDirectoryEnumerationOptions())
            //print(directoryUrls)
            let Files = directoryUrls.filter{ $0.pathExtension == Extension }.map{ $0.lastPathComponent }
            print("\(Extension) FILES:\n" + Files.description)
        } catch let error as NSError {
            print(error.localizedDescription)
        }
    }

2 个答案:

答案 0 :(得分:2)

for file in Files {
    try NSFileManager.defaultManager().removeItemAtPath(file)
}

答案 1 :(得分:0)

对于Swift 3和Swift 4.0

$array1 = ['mp', 'tm', 'de', 'HK'];
$array2 = ['MAP', 'TM', "DECIMAL", '字'];

$mystring = "samplemp \t okay hellotm";
preg_match_all('/\s+/', $mystring,$space_array);
$space_array = isset($space_array[0])?$space_array[0]:$space_array;
$test_array = preg_split('/\s+/', $mystring);
$change_array= array();
$new_str = "";
foreach ($test_array as $key => $value) {         
    $last = substr($value, -2);
    $newlast = str_replace($array1, $array2, $last);
    if ($last != $newlast){
        $value = substr($value, 0, strlen($value)-2).$newlast;
    }
    $value .= isset($space_array[$key])?$space_array[$key]:"";
    $change_array[] = $value;    
}
var_dump(implode("", $change_array));