[SWIFT] Delete folders and files with File Manager

Introduction

In the previous Article, I wrote about how to add video, audio, etc. to the terminal using File Manager. Here's how to remove them.

Errors that may be resolved

Domain=NSCocoaErrorDomain Code=4 "” couldn’t be removed." UserInfo={NSUserStringVariant=( Remove ), NSFilePath=/var/mobile/Containers/Data/Application/EB92E676-C1F0-4B9A-8D82-D86D7186B2F3/Documents/dfg, NSUnderlyingError=0x2814ded00 {Error Domain=NSPOSIXErrorDomain Code=2 "No such file or directory"}}

Goal

iOS App
    ├── Documents --- test.txt //Delete files and folders added here
    ├── Library
    │   ├── Caches
    │   └── Preferences
    └── tmp

Source code

func removeItem(_ itemName: String) {
        let fileManager = FileManager.default
        var pathString = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        if !fileManager.fileExists(atPath: pathString + "/" + itemName) {
            print("The specified file or folder does not exist")
            return
        }
        pathString = "file://" + pathString + "/" + itemName
        guard let path = URL(string: pathString) else { return }
        do {
            try fileManager.removeItem(at: path)
            print("Successful")
        } catch let error {
            print("failed\(error)")
        }
    }

flow

Prepare the path to Documents with pathString and use fileExists to check if the folder or file entered as an argument after Documents exists. (The error when the specified item does not exist will be picked up on the 13th line, so it is not necessary here.) Then change the path, convert it to a URL type and remove it using removeItem.

Recommended Posts

Delete folders and files with File Manager
Save files and folders using File Manager
Drag and drop files with JavaFX
[Java] Reading and writing files with OpenCSV
[Kotlin] Delete files with duplicate contents [Java]
Rails "How to delete NO FILE migration files"
[Java] Convert and import file values with OpenCSV
[Review] Reading and writing files with java (JDK6)
Connect with port forwarding with SSH and send and receive files
[Java] Development with multiple files using package and import