2016-01-22 77 views
3

我正在嘗試創建一個函數,可以使用給定的文件擴展名刪除文檔目錄中的多個文件。刪除文檔目錄中的多個文件

到目前爲止,我有下面的功能,但我可以在更舊的版本上完成它刪除文件創建?

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

回答

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

謝謝你,但是這個工作,從列表中選擇一個文件不能被刪除---「20-01-2016_142531.mov」 couldn不知道爲什麼? – SNos

+0

該方法在這種情況下應該拋出一個錯誤,你可以調試它應該告訴你原因,也許該文件是由另一個進程打開的 – Christian

+0

我能看到的唯一錯誤是' 「20-01-2016_142531.mov」無法移除。「# – SNos

0

對於斯威夫特3和雨燕4.0

let fileManager : FileManager = FileManager.default 
    let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory 
    let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask 
    let paths : NSArray = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true) as NSArray 
    let documentsDirectory = paths.object(at: 0) as! NSString 
    print(documentsDirectory) 
    let contents : NSArray = try! fileManager.contentsOfDirectory(atPath: documentsDirectory as String) as NSArray 
    let enumerator : NSEnumerator = contents.objectEnumerator() 
    while let element = enumerator.nextObject() as? String 
    { 
     let fileName = element as NSString 
     if fileName.pathExtension == "m4a" 
     { 
      let pathOfFile = documentsDirectory.appendingPathComponent(fileName as String) 
      try! fileManager.removeItem(atPath: pathOfFile) 

     } 
    }