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]);
}
}
Swift 3.0:
func removeImage(itemName:String, fileExtension: String) {
let fileManager = FileManager.default
let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
guard let dirPath = paths.first else {
return
}
let filePath = "\(dirPath)/\(itemName).\(fileExtension)"
do {
try fileManager.removeItem(atPath: filePath)
} catch let error as NSError {
print(error.debugDescription)
}}
Thanks to @Anil Varghese, I wrote very similiar code in swift 2.0:
static func removeImage(itemName:String, fileExtension: String) {
let fileManager = NSFileManager.defaultManager()
let nsDocumentDirectory = NSSearchPathDirectory.DocumentDirectory
let nsUserDomainMask = NSSearchPathDomainMask.UserDomainMask
let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
guard let dirPath = paths.first else {
return
}
let filePath = "\(dirPath)/\(itemName).\(fileExtension)"
do {
try fileManager.removeItemAtPath(filePath)
} catch let error as NSError {
print(error.debugDescription)
}
}