Delete specified file from document directory

IosObjective CXcodeNsdocumentdirectory

Ios Problem Overview


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

Ios Solutions


Solution 1 - Ios

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]);
  }
}

Solution 2 - Ios

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

Solution 3 - Ios

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

Solution 4 - Ios

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

Solution 5 - Ios

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

Solution 6 - Ios

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

Solution 7 - Ios

    NSError *error;
    [[NSFileManager defaultManager] removeItemAtPath:new_file_path_str error:&error];
    if (error){
        NSLog(@"%@", error);
    }

Solution 8 - Ios

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

Solution 9 - Ios

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
                }
            }

Solution 10 - Ios

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser1982396View Question on Stackoverflow
Solution 1 - IosAnil VargheseView Answer on Stackoverflow
Solution 2 - IosRoman BarzyczakView Answer on Stackoverflow
Solution 3 - IosFreeGorView Answer on Stackoverflow
Solution 4 - IosSai kumar ReddyView Answer on Stackoverflow
Solution 5 - IosChris LoonamView Answer on Stackoverflow
Solution 6 - Iosuser3182143View Answer on Stackoverflow
Solution 7 - IosAlex SpencerView Answer on Stackoverflow
Solution 8 - IosAndrea LeganzaView Answer on Stackoverflow
Solution 9 - IosMountain ManView Answer on Stackoverflow
Solution 10 - IosAzonView Answer on Stackoverflow