2015-12-19 12 views
13

Ho scaricato alcuni file PDF nella mia app e desidero eliminarli alla chiusura dell'applicazione.Elimina i file nella directory iOS utilizzando Swift

Per qualche ragione non funziona:

Creazione del file:

let reference = "test.pdf"  
let RequestURL = "http://xx/_PROJEKTE/xx\(self.reference)" 
let ChartURL = NSURL(string: RequestURL) 

//download file 
let documentsUrl = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first! as NSURL 
let destinationUrl = documentsUrl.URLByAppendingPathComponent(ChartURL!.lastPathComponent!) 
if NSFileManager().fileExistsAtPath(destinationUrl.path!) { 
    print("The file already exists at path") 
} else { 
    // if the file doesn't exist 
    // just download the data from your url 
    if let ChartDataFromUrl = NSData(contentsOfURL: ChartURL!){ 
     // after downloading your data you need to save it to your destination url 
     if ChartDataFromUrl.writeToURL(destinationUrl, atomically: true) { 
      print("file saved") 
      print(destinationUrl) 
     } else { 
      print("error saving file") 
     } 
    } 
} 

Poi voglio chiamare la funzione test() per rimuovere gli elementi, in questo modo:

func test(){ 

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

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

Ho il sospetto che si vuole considerare l'utilizzo di '.CachesDirectory' piuttosto che' .DocumentDirectory' per il salvataggio e l'eliminazione di questi file. – TwoStraws

+0

ho provato a salvare il mio file ma non ha funzionato –

+1

Dovresti assolutamente leggere [best practice di backup app] (https://developer.apple.com/library/ios/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/PerformanceTips /PerformanceTips.html#//apple_ref/doc/uid/TP40007072-CH7-SW17) e [QA1719] (https://developer.apple.com/library/ios/qa/qa1719/_index.html) quindi. – TwoStraws

risposta

8

Credo che il tuo problema sia su questa linea:

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

Si sta utilizzando contentsOfDirectoryAtPath() con qualcosa che è un NSURL. Puoi scegliere tra stringhe di percorso o URL, non provare a mescolarli entrambi. Per svuotare la tua prossima domanda, gli URL sono preferiti. Prova a utilizzare contentsOfDirectoryAtURL() e removeItemAtURL().

Un'altra cosa curiosa da considerare una volta risolto quanto sopra: perché stai utilizzando NSTemporaryDirectory() per il percorso del file quando tenti di eliminare? Stai leggendo la directory del documento e dovresti usarla.

+0

c'è un modo per eliminare "CachesDirectory completa()"? –

+0

I documenti e la libreria/cache non devono essere cancellati. Aggiungi e rimuovi i file se lo desideri, ma non eliminarli. Nota: Llibrary/Caches devono essere cancellati per te da iOS secondo necessità. – TwoStraws

+0

così ho capito bene -> non eliminare i file memorizzati in CachesDirectory(), iOS li "eliminiamo" da soli? –

29

Questo codice funziona per me. Ho rimosso tutte le immagini che sono state memorizzate nella cache.

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

**** Aggiornamento rapido 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)") 
     } 
+1

le prime 3 righe (Swift3) sono fantastiche e mi hanno aiutato con CRUD per il mio registratore/lettore audio (cioè il dittafono)! Grazie! –

+0

abbinamenti perfetti è perfettamente funzionante. Anche con cartelle condivise. molte grazie –

Problemi correlati