简体   繁体   中英

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

If I attempt to remove a file using the FileManager class I get an error.

The function below returns true , which means that I need to set the delete privileges attributes. However I haven't found an example on how to do it.

func isDeletableFile(atPath path: String) -> Bool

Any help?

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

There is a common misunderstanding:

In the file system a you have to call path on the URL to get the path

fileManager.isDeletableFile(atPath: fileAsNSURL.path)

absoluteString returns the (percent escaped) string representation of the URL starting with the scheme ( http:// , file:// )


For example you have an URL (don't use NSURL in Swift 3):

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM