115

I want to delete an image from my app document directory. Code I have written to delete image is:

 -(void)removeImage:(NSString *)fileName
{
    fileManager = [NSFileManager defaultManager];
    paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    documentsPath = [paths objectAtIndex:0];
    filePath = [documentsPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@", fileName]];
    [fileManager removeItemAtPath:filePath error:NULL];
    UIAlertView *removeSuccessFulAlert=[[UIAlertView alloc]initWithTitle:@"Congratulation:" message:@"Successfully removed" delegate:self cancelButtonTitle:@"Close" otherButtonTitles:nil];
    [removeSuccessFulAlert show];
}

Its working partially. This code deleting file from directory, but when I'm checking for the contents in directory, it still showing the image name there. I want to completely remove that file from directory. What should I change in the code to do the same? Thanks

3
  • 4
    It is likely throwing an error which you ignored, add NSError instance and check it after removeItemAtPath Feb 22, 2013 at 6:16
  • 1
    use - (BOOL)fileExistsAtPath:(NSString *)path; to check whether the image exist , if it return YES, it means your remove is failed Feb 22, 2013 at 6:23
  • Just tested it and it's definitely getting removed and the removal is reflected in contentsOfDirectoryAtPath (i.e. no directory caching involved here). So you must have some simple error in play which should become apparent when you look at the NSError contents.
    – Rob
    Feb 22, 2013 at 6:28

10 Answers 10

241

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]);
  }
}
4
  • I can create file in Document directory but always get error when try to remove it. Do you have any ideas?
    – Vadym
    Apr 5, 2013 at 4:57
  • I solved it. The problem was: I created new file without any attributes, and as I understand, it gave a default attribute NSFileImmutable YES. Or something like that. Sorry can't show sources now. But the problem was trivial.
    – Vadym
    Apr 8, 2013 at 14:22
  • Is checking file exist or not is necessary? Nov 23, 2018 at 11:05
  • it deletes file from directory but it still showing image in photos of simulator Dec 26, 2018 at 6:45
57

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)
  }
}
5
  • Why make the function static?
    – CalZone
    Sep 25, 2016 at 1:01
  • It's up to you. It's no necessary Sep 25, 2016 at 6:44
  • Is there a way to check whether the file still exists before/after calling the function to make sure it's been removed?
    – luke
    Feb 7, 2017 at 16:47
  • 1
    yes sure: let fileManager = FileManager.default if fileManager.fileExists(atPath: filePath!) { print("FILE AVAILABLE") } else { print("FILE NOT AVAILABLE") } Feb 9, 2017 at 8:26
  • Swift 3.0 version above works well on Swift 5.2. Thank you!
    – David_2877
    Jan 3, 2021 at 4:57
11

Swift 2.0:

func removeOldFileIfExist() {
    let paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)
    if paths.count > 0 {
        let dirPath = paths[0]
        let fileName = "someFileName"
        let filePath = NSString(format:"%@/%@.png", dirPath, fileName) as String
        if NSFileManager.defaultManager().fileExistsAtPath(filePath) {
            do {
                try NSFileManager.defaultManager().removeItemAtPath(filePath)
                print("old image has been removed")
            } catch {
                print("an error during a removing")
            }
        }
    }
}
9

In Swift both 3&4

 func removeImageLocalPath(localPathName:String) {
            let filemanager = FileManager.default
            let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory,.userDomainMask,true)[0] as NSString
            let destinationPath = documentsPath.appendingPathComponent(localPathName)
 do {
        try filemanager.removeItem(atPath: destinationPath)
        print("Local path removed successfully")
    } catch let error as NSError {
        print("------Error",error.debugDescription)
    }
    }

or This method can delete all local file

func deletingLocalCacheAttachments(){
        let fileManager = FileManager.default
        let documentsURL = fileManager.urls(for: .documentDirectory, in: .userDomainMask)[0]
        do {
            let fileURLs = try fileManager.contentsOfDirectory(at: documentsURL, includingPropertiesForKeys: nil)
            if fileURLs.count > 0{
                for fileURL in fileURLs {
                    try fileManager.removeItem(at: fileURL)
                }
            }
        } catch {
            print("Error while enumerating files \(documentsURL.path): \(error.localizedDescription)")
        }
    }
1
  • 2
    Add the following in the last line instead to direct try. do { try filemanager.removeItem(atPath: destinationPath) print("Deleted") } catch { print("Not Deleted") } Aug 27, 2018 at 10:19
5

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

3

I want to delete my sqlite db from document directory.I delete the sqlite db successfully by below answer

NSString *strFileName = @"sqlite";
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];

NSArray *contents = [fileManager contentsOfDirectoryAtPath:documentsDirectory error:NULL];
NSEnumerator *enumerator = [contents objectEnumerator];
NSString *filename;
while ((filename = [enumerator nextObject])) {
    NSLog(@"The file name is - %@",[filename pathExtension]);
    if ([[filename pathExtension] isEqualToString:strFileName]) {
       [fileManager removeItemAtPath:[documentsDirectory stringByAppendingPathComponent:filename] error:NULL];
        NSLog(@"The sqlite is deleted successfully");
    }
}
2
    NSError *error;
    [[NSFileManager defaultManager] removeItemAtPath:new_file_path_str error:&error];
    if (error){
        NSLog(@"%@", error);
    }
2

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")
            }
        }
    }
}
0

You can double protect your file removal with NSFileManager.defaultManager().isDeletableFileAtPath(PathName) As of now you MUST use do{}catch{} as the old error methods no longer work. isDeletableFileAtPath() is not a "throws" (i.e. "public func removeItemAtPath(path: String) throws") so it does not need the do...catch

let killFile = NSFileManager.defaultManager()

            if (killFile.isDeletableFileAtPath(PathName)){


                do {
                  try killFile.removeItemAtPath(arrayDictionaryFilePath)
                }
                catch let error as NSError {
                    error.description
                }
            }
0

If you are interesting in modern api way, avoiding NSSearchPath and filter files in documents directory, before deletion, you can do like:

let fileManager = FileManager.default
let keys: [URLResourceKey] = [.nameKey, .isDirectoryKey]
let options: FileManager.DirectoryEnumerationOptions = [.skipsHiddenFiles, .skipsPackageDescendants]
guard let documentsUrl = fileManager.urls(for: .documentDirectory, in: .userDomainMask).last,
      let fileEnumerator = fileManager.enumerator(at: documentsUrl,
                                                  includingPropertiesForKeys: keys,
                                                  options: options) else { return }

let urls: [URL] = fileEnumerator.flatMap { $0 as? URL }
                                .filter { $0.pathExtension == "exe" }
for url in urls {
   do {
      try fileManager.removeItem(at: url)
   } catch {
      assertionFailure("\(error)")
   }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.