I want to delete an image from my app document directory. Code I have written to delete image is:
-(void)removeImage:(NSString *)fileName
{
fileManag
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]);
}
}
Instead of having the error set to NULL, have it set to
NSError *error;
[fileManager removeItemAtPath:filePath error:&error];
if (error){
NSLog(@"%@", error);
}
this will tell you if it's actually deleting the file
FreeGor version converted to Swift 3.0
func removeOldFileIfExist() {
let paths = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)
if paths.count > 0 {
let dirPath = paths[0]
let fileName = "filename.jpg"
let filePath = NSString(format:"%@/%@", dirPath, fileName) as String
if FileManager.default.fileExists(atPath: filePath) {
do {
try FileManager.default.removeItem(atPath: filePath)
print("User photo has been removed")
} catch {
print("an error during a removing")
}
}
}
}
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)
}
}