2017-01-23 2 views
0

Si je tente de supprimer un fichier en utilisant la classe FileManager, je reçois une erreur.Swift 3.0 et iOS: Comment définir les privilèges de suppression d'un fichier dans Swift

La fonction retourne ci-dessous vrai, ce qui signifie que je dois définir les privilèges de suppressionattributs. Cependant, je haven't trouvé un exemple sur la façon de le faire.

func isDeletableFile(atPath path: String) -> Bool 

Une aide?

code:

func fileManager(_ fileManager: FileManager, shouldRemoveItemAtPath path: String) -> Bool { 
    // print("Should remove invoked for path \(path)") 
    return true 
} 

func fileManager(_ fileManager: FileManager, shouldProceedAfterError error: Error, removingItemAt URL: URL) -> Bool { 
    //print("Should process") 
    return true 
} 

func deleteAllFiles(subPath : String) { 
    var url = Bundle.main.bundleURL 
    url = url.appendingPathComponent(subPath) 

    let fileManager = FileManager.default 
    fileManager.delegate = self 

    if let enumerator = fileManager.enumerator(at: url, includingPropertiesForKeys: nil) { 
     for file in enumerator { 
      let fileAsNSURL = file as! NSURL 
      print("") 
      print("Deleting: \(fileAsNSURL.absoluteString!)") 
      print("") 

      do { 
       // I would like to set the deletable permissions before checking this.. 
       if (fileManager.isDeletableFile(atPath: fileAsNSURL.absoluteString!)){ 
        try fileManager.removeItem(atPath: fileAsNSURL.absoluteString!) 
       } 
       else{ 
        print("its not deletable") 
       } 
      } 
      catch let error { 
       print("file-delete-error:\n\(error) for path \(fileAsNSURL.absoluteString!)") 
      } 
     } 
    } 
} 
+1

http://stackoverflow.com/questions/40642217/uiimagecontentsoffile-returning-nil-despite-file-existing-in-caches-directory/40643037?s=1|0.8206#40643037 –

+1

Merci! Cela a aidé à résoudre – mm24

Répondre

1

Il y a un malentendu commun:

Dans le système de fichiers un, vous devez appeler path sur l'URL pour obtenir le chemin

fileManager.isDeletableFile(atPath: fileAsNSURL.path) 

absoluteString renvoie la chaîne (pourcentage échappé) entation de l'URL commençant par le schéma (http://, file://)


Par exemple, vous avez une URL (ne pas utiliser NSURL à Swift 3):

let url = URL(fileURLWithPath:"/Users/myUser/Application Support") 
  • url.path retours "/Users/myUser/Application Support"
  • url.absoluteString renvoie "file:///Users/myUser/Application%20Support"