Nitish
Nitish

Reputation: 14123

NSDocumentDirectory remove folder

I have created a folder inside documents directory using :

fileManager.createDirectory(atPath:ziPFolderPath,withIntermediateDirectories: false, attributes: nil)  

In this folder I have placed few files.
Later in the app, I want to delete not just the files inside the above folder, but also the folder.
FileManager supports removeItem function but I am wondering if it removes the folder as well.

Upvotes: 14

Views: 9897

Answers (3)

user1039695
user1039695

Reputation: 1061

Swift 5

Also you should check if file exist at path or not and check for error also.

do {
    let fileManager = FileManager.default

    // Check if file exists
    if fileManager.fileExists(atPath: urlfilePath) {
        // Delete file
        try fileManager.removeItem(atPath: urlfilePath)
    } else {
        print("File does not exist")
    }
} catch {
    print("An error took place: \(error)")
}

Upvotes: 6

Nirav D
Nirav D

Reputation: 72460

Yes it will delete folder also.

From the documentation of: - removeItem(at:)

Removes the file or directory at the specified URL.

From the documentation of: - removeItem(atPath:)

Removes the file or directory at the specified path.

Edit: You can call it like this way.

try? FileManager.default.removeItem(at: URL(fileURLWithPath: ziPFolderPath))
//OR
try? FileManager.default.removeItem(atPath: ziPFolderPath)

Upvotes: 23

Mohsin Khan
Mohsin Khan

Reputation: 108

-(BOOL)removeItemAtPath:(NSString *)path 
                   error:(NSError * _Nullable *)error;

path is the string indicating directory or folder to remove. Its a NSFileManager method.

you can also check here https://developer.apple.com/reference/foundation/nsfilemanager/1408573-removeitematpath?language=objc

Upvotes: 0

Related Questions