2015-09-29 27 views
22

Ho creato una directory Temp per memorizzare alcuni file:Elimina i file dalla directory all'interno della directory dei documenti?

//MARK: -create save delete from directory 
func createTempDirectoryToStoreFile(){ 
    var error: NSError? 
    let paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true) 
    let documentsDirectory: AnyObject = paths[0] 
    tempPath = documentsDirectory.stringByAppendingPathComponent("Temp") 

    if (!NSFileManager.defaultManager().fileExistsAtPath(tempPath!)) { 

     NSFileManager.defaultManager() .createDirectoryAtPath(tempPath!, withIntermediateDirectories: false, attributes: nil, error: &error) 
    } 
} 

Va bene, ora voglio eliminare tutti i file che si trovano all'interno della directory ... ho provato, come di seguito:

func clearAllFilesFromTempDirectory(){ 

    var error: NSErrorPointer = nil 
    let dirPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as! String 
    var tempDirPath = dirPath.stringByAppendingPathComponent("Temp") 
    var directoryContents: NSArray = fileManager.contentsOfDirectoryAtPath(tempDirPath, error: error)! 

    if error == nil { 
     for path in directoryContents { 
      let fullPath = dirPath.stringByAppendingPathComponent(path as! String) 
      let removeSuccess = fileManager.removeItemAtPath(fullPath, error: nil) 
     } 
    }else{ 

     println("seomthing went worng \(error)") 
    } 
} 

Ho notato che i file sono ancora lì ... Cosa sto facendo male?

+0

Si consiglia di aggiornare il tuo Xcode. –

+0

why ???? its 6.4 .. –

+0

Altrimenti verrai lasciato indietro. Dovresti sempre usare la versione del negozio di apple –

risposta

14

Due cose, utilizzare la directory temp e passare un secondo errore a fileManager.removeItemAtPath e posizionarlo in a per vedere cosa non è riuscito. Inoltre, non dovresti controllare se l'errore è impostato, ma piuttosto se un metodo ha dati di ritorno.

func clearAllFilesFromTempDirectory(){ 

    var error: NSErrorPointer = nil 
    let dirPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as! String 
    var tempDirPath = dirPath.stringByAppendingPathComponent("Temp") 
    var directoryContents: NSArray = fileManager.contentsOfDirectoryAtPath(tempDirPath, error: error)? 

    if directoryContents != nil { 
     for path in directoryContents { 
      let fullPath = dirPath.stringByAppendingPathComponent(path as! String) 
      if fileManager.removeItemAtPath(fullPath, error: error) == false { 
       println("Could not delete file: \(error)") 
      } 
     } 
    } else { 
     println("Could not retrieve directory: \(error)") 
    } 
} 

per ottenere l'uso della directory temporanea corretta NSTemporaryDirectory()

+0

grazie ottengo questo errore come Impossibile eliminare il file: 0x0000000000000000 –

+0

Hmm che è un puntatore nullo, puoi ottenere il percorso ordinato in 'fullPath'? forse c'è un problema lì. – rckoenes

+1

ho trovato il mio errore grazie .... –

33

Nel caso in cui qualcuno ha bisogno di questo per le ultime versioni Swift/Xcode: ecco un esempio per rimuovere tutti i file dalla cartella Temp:

2.x Swift:

func clearTempFolder() { 
    let fileManager = NSFileManager.defaultManager() 
    let tempFolderPath = NSTemporaryDirectory() 
    do { 
     let filePaths = try fileManager.contentsOfDirectoryAtPath(tempFolderPath) 
     for filePath in filePaths { 
      try fileManager.removeItemAtPath(tempFolderPath + filePath) 
     } 
    } catch { 
     print("Could not clear temp folder: \(error)") 
    } 
} 

Swift 3.x e Swift 4:

func clearTempFolder() { 
    let fileManager = FileManager.default 
    let tempFolderPath = NSTemporaryDirectory() 
    do { 
     let filePaths = try fileManager.contentsOfDirectory(atPath: tempFolderPath) 
     for filePath in filePaths { 
      try fileManager.removeItem(atPath: tempFolderPath + filePath) 
     } 
    } catch { 
     print("Could not clear temp folder: \(error)") 
    } 
} 
+0

Come posso ottenere il percorso da una cartella specifica? –

+0

@amirt Puoi aggiungere una nuova domanda per questo?È un argomento diverso e richiede un po 'più di spiegazione da parte tua. – joern

12

Swift 3:

func clearTempFolder() { 
    let fileManager = FileManager.default 
    let tempFolderPath = NSTemporaryDirectory() 

    do { 
     let filePaths = try fileManager.contentsOfDirectory(atPath: tempFolderPath) 
     for filePath in filePaths { 
      try fileManager.removeItem(atPath: NSTemporaryDirectory() + filePath) 
     } 
    } catch let error as NSError { 
     print("Could not clear temp folder: \(error.debugDescription)") 
    } 
} 
4

Swift 4.0 esempio che rimuove tutti i file da una cartella ad esempio "diskcache" nella directory documenti. Ho trovato poco chiaro gli esempi sopra riportati perché hanno utilizzato lo NSTemporaryDirectory() + filePath che non è in stile "url". Per la vostra comodità:

func clearDiskCache() { 
     let fileManager = FileManager.default 
     let myDocuments = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first! 
     let diskCacheStorageBaseUrl = myDocuments.appendingPathComponent("diskCache") 
     guard let filePaths = try? fileManager.contentsOfDirectory(at: diskCacheStorageBaseUrl, includingPropertiesForKeys: nil, options: []) else { return } 
     for filePath in filePaths { 
      try? fileManager.removeItem(at: filePath) 
     } 
    } 
+0

bello questo è utile per swift 4, può confermare funziona! – VTS12

0

Utilizzando file

https://github.com/JohnSundell/Files

do { 
     for folder:Folder in (FileSystem().documentFolder?.subfolders)! { 
      try folder.delete() 
     } 
    } catch _ { 
     print("Error") 
    } 
Problemi correlati