2017-01-23 103 views
0

如果我尝试使用FileManager类删除文件,则会出现错误。Swift 3.0和iOS:如何在Swift中设置文件的删除权限

以下功能返回true,这意味着我需要设置删除权限属性。然而我在haven't找到了一个关于如何去做的例子。

func isDeletableFile(atPath path: String) -> Bool 

任何帮助?

代码:

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

谢谢!它确实有助于解决 – mm24

回答

1

有一个常见的误区:

在文件系统中你必须调用path的URL来获取路径

fileManager.isDeletableFile(atPath: fileAsNSURL.path) 

absoluteString返回(百分号转义)字符串repres首先是方案的URL entation(http://file://


例如你有一个URL(不斯威夫特3使用NSURL):

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