Swift 3.0 and iOS: 如何在Swift中设置文件的删除权限

Swift 3.0 and iOS: How to set the delete privileges of a file in Swift

如果我尝试使用 FileManager class 删除文件,我会收到错误消息。

returns下面的函数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!)")
            }
        }
    }
}

有一个普遍的误解:

在文件系统中,您必须在 URL 上调用 path 以获取路径

fileManager.isDeletableFile(atPath: fileAsNSURL.path)

absoluteString returns URL 以方案 (http://, file://)[=21= 开头的(转义百分比)字符串表示]


例如你有一个 URL(不要在 Swift 3 中使用 NSURL):

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