Delete Specified File from Document Directory

Delete specified file from document directory

I checked your code. It's working for me. Check any error you are getting using the modified code below

- (void)removeImage:(NSString *)filename
{
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];

NSString *filePath = [documentsPath stringByAppendingPathComponent:filename];
NSError *error;
BOOL success = [fileManager removeItemAtPath:filePath error:&error];
if (success) {
UIAlertView *removedSuccessFullyAlert = [[UIAlertView alloc] initWithTitle:@"Congratulations:" message:@"Successfully removed" delegate:self cancelButtonTitle:@"Close" otherButtonTitles:nil];
[removedSuccessFullyAlert show];
}
else
{
NSLog(@"Could not delete file -:%@ ",[error localizedDescription]);
}
}

Delete files from directory inside Document directory?

Two things, use the temp directory and second pass an error to the fileManager.removeItemAtPath and place it in a if to see what failed. Also you should not be checking if the error is set but rather whether a methods has return data.

func clearAllFilesFromTempDirectory(){

var error: NSErrorPointer = nil
let dirPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as! String
var tempDirPath = dirPath.stringByAppendingPathComponent("Temp")
var directoryContents: NSArray = fileManager.contentsOfDirectoryAtPath(tempDirPath, error: error)?

if directoryContents != nil {
for path in directoryContents {
let fullPath = dirPath.stringByAppendingPathComponent(path as! String)
if fileManager.removeItemAtPath(fullPath, error: error) == false {
println("Could not delete file: \(error)")
}
}
} else {
println("Could not retrieve directory: \(error)")
}
}

To get the correct temporary directory use NSTemporaryDirectory()

How do I delete a file in my apps documents directory?

NSFileManager is a very handy tool:

[[NSFileManager defaultManager] removeItemAtPath: pathToFile error: &error];

Remove all files from within documentDirectory in Swift

First of all the error occurs because the signature of the API is wrong. It's just removeItem(at:) without the other parameters.

A second issue is that you are going to delete the Documents directory itself rather than the files in the directory which you are discouraged from doing that.

You have to get the contents of the directory and add a check for example to delete only MP3 files. A better solution would be to use a subfolder.

let documentsUrl =  FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!

do {
let fileURLs = try FileManager.default.contentsOfDirectory(at: documentsUrl,
includingPropertiesForKeys: nil,
options: .skipsHiddenFiles)
for fileURL in fileURLs where fileURL.pathExtension == "mp3" {
try FileManager.default.removeItem(at: fileURL)
}
} catch { print(error) }

Side note: It is highly recommended to use always the URL related API of FileManager.

how to delete the specific item in the document directory ios objective c

You can try like this way

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
if (filePathsArray.count >= 6) {
for (NSInteger i=filePathsArray.count-6; i < filePathsArray.count; i++) {
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:[filePathsArray objectAtIndex:i]];
if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
NSError *error;
if (![[NSFileManager defaultManager] removeItemAtPath:filePath error:&error]) {
NSLog(@"Delete error: %@", error);
}
}
}
}

Swift -Delete Custom Folder From Documents Directory

In the function parameter should I pass in "MyFolder" or "/MyFolder"?

"MyFolder", because appendingPathComponent adds / automatically.

How to delete the contents of the Documents directory (and not the Documents directory itself)?

Try this:

NSString *folderPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]; 
NSError *error = nil;
for (NSString *file in [[NSFileManager defaultManager] contentsOfDirectoryAtPath:folderPath error:&error]) {
[[NSFileManager defaultManager] removeItemAtPath:[folderPath stringByAppendingPathComponent:file] error:&error];
}

Swift delete all files from particular Document Directory Location

You are mixing up URL and String path

Either use the String related API

try fm.removeItem(atPath: myurl.path) // NEVER use .absoluteString for a file system path

or use the URL related API (recommended)

try fm.removeItem(at: myurl)

To remove all files get the file URLs in the enclosing directory with contentsOfDirectory(at:includingPropertiesForKeys:options:) and remove one by one

let fileManager = FileManager.default
do {
let documentDirectoryURL = try fileManager.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
let fileURLs = try fileManager.contentsOfDirectory(at: documentDirectoryURL, includingPropertiesForKeys: nil, options: .skipsHiddenFiles)
for url in fileURLs {
try fileManager.removeItem(at: url)
}
} catch {
print(error)
}

Document Directory: delete file and rename remaining files in Swift 4.2

This might need some tweaking, but what about the following approach (in pseudo code) after you delete the file.

let directoryContent = try FileManager.default.contentsOfDirectory(at:   self.folderPath! as URL, includingPropertiesForKeys: nil, options: [])
var index = 1
var newImageArray:[URL] = []
for fileURL in directoryContent
{
let newFileName = String(format: "image%d.jpg", index)
let newFilePathURL = makePathAsYouWere()
_ = try? self.fileManager.moveItem(atPath: fileURL, toPath: newFilePathURL)
index += 1
newImageArray.append(newFilePathURL)
}

self.imageArray = newImageArray

collectionView.reload()

Essentially, once you remove the files you will have a set of files that you can iterate over. That list might need to be sorted to get them in the correct order, but once they are sorted (file1, file2, file4, file5). You should be able to rename each sequentially to get them back in numerical order with no gaps since the approach above does not care about the index of the old file.

For the image array, you should just be able to create a new one with the new file paths your are creating, replace the old array and then trigger a reload. With this, you also don't have to remove the delete item from the image array, it will be removed when you rebuild things.

Let me know if that is enough to get you started, otherwise, I can try to pull together a fully worked example.

Delete a file selected by user from Files Directory in Swift 4?

you need to create file path by appending filename to base url for your directory

func delete(fileName : String)->Bool{
let fileManager = FileManager.default
let docDir = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
let filePath = docDir.appendingPathComponent(fileName)
do {
try FileManager.default.removeItem(at: filePath)
print("File deleted")
return true
}
catch {
print("Error")
}
return false
}


Related Topics



Leave a reply



Submit