Usuń określony plik z katalogu dokumentów


111

Chcę usunąć obraz z katalogu dokumentów aplikacji. Kod, który napisałem, aby usunąć obraz to:

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

Działa częściowo. Ten kod usuwa plik z katalogu, ale kiedy sprawdzam zawartość w katalogu, nadal pokazuje tam nazwę obrazu. Chcę całkowicie usunąć ten plik z katalogu. Co powinienem zmienić w kodzie, aby zrobić to samo? Dzięki


4
Jest prawdopodobne, rzucanie błąd którego ignorowane, dodać instancję NSError i sprawdzić go po removeItemAtPath
— Dmitry Shevchenko

1
use - (BOOL) fileExistsAtPath: (NSString *) ścieżka; aby sprawdzić, czy exist obrazu, jeśli zwróci TAK, to znaczy, że nie powiodła usuń
— Guo Luchuan

Właśnie go przetestowałem i na pewno zostanie usunięty, a usunięcie jest odzwierciedlone w contentsOfDirectoryAtPath(tj. Nie ma tu buforowania katalogu). Więc musisz mieć jakiś prosty błąd w grze, który powinien stać się widoczny, gdy spojrzysz na NSErrorzawartość.
— Rob

Odpowiedzi:


238

Sprawdziłem twój kod. To działa na mnie. Sprawdź każdy błąd, który otrzymujesz, używając zmodyfikowanego kodu poniżej

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

Mogę utworzyć plik w katalogu Document, ale zawsze pojawia się błąd przy próbie jego usunięcia. Czy masz jakies pomysły?
— Vadim,

Rozwiązałem to. Problem polegał na tym, że utworzyłem nowy plik bez żadnych atrybutów i jak rozumiem nadał domyślny atrybut NSFileImmutable YES. Czy jakoś tak. Przepraszamy, nie mogę teraz pokazać źródeł. Ale problem był trywialny.
— Vadim,

Czy plik kontrolny istnieje, czy nie jest potrzebny?
— Sangram Shivankar

usuwa plik z katalogu, ale nadal wyświetla obraz na zdjęciach symulatora
— Sagar koyani

55

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

Dzięki @Anil Varghese napisałem bardzo podobny kod w 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)
  }
}

Dlaczego funkcja jest statyczna?
— CalZone

To zależy od Ciebie. To nie jest konieczne
— Roman Barzyczak

Czy istnieje sposób sprawdzenia, czy plik nadal istnieje przed / po wywołaniu funkcji, aby upewnić się, że został usunięty?
— Łukasz

1
tak jasne: let fileManager = FileManager.default if fileManager.fileExists (atPath: filePath!) {print ("FILE AVAILABLE")} else {print ("FILE NOT AVAILABLE")}
— Roman Barzyczak

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

8

W Swift zarówno 3, jak i 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)
    }
    }

lub Ta metoda może usunąć cały plik lokalny

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

2
Zamiast tego dodaj poniższe w ostatnim wierszu, aby bezpośrednio spróbować. do {try filemanager.removeItem (atPath: destinationPath) print ("Deleted")} catch {print ("Not Deleted")}
— Abhirajsinh Thakore

5

Zamiast ustawiać błąd na NULL, ustaw go na

NSError *error;
[fileManager removeItemAtPath:filePath error:&error];
if (error){
NSLog(@"%@", error);
}

dzięki temu dowiesz się, czy faktycznie usuwa plik


3

Chcę usunąć moją bazę danych sqlite z katalogu dokumentów. Usunąłem bazę danych sqlite pomyślnie, korzystając z poniższej odpowiedzi

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

1

Wersja FreeGor przekonwertowana do 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

Możesz podwójnie zabezpieczyć usuwanie plików za pomocą NSFileManager.defaultManager (). IsDeletableFileAtPath (PathName) Od teraz MUSISZ używać do {} catch {}, ponieważ stare metody błędów już nie działają. isDeletableFileAtPath () nie jest „rzutami” (tj. „publiczną func removeItemAtPath (ścieżka: String) zgłasza”), więc nie potrzebuje do ... catch

let killFile = NSFileManager.defaultManager()

            if (killFile.isDeletableFileAtPath(PathName)){


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

0

Jeśli interesujesz się nowoczesnym interfejsem API, unikając NSSearchPath i filtruj pliki w katalogu dokumentów, przed usunięciem możesz zrobić tak:

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)")
   }
}
Korzystając z naszej strony potwierdzasz, że przeczytałeś(-aś) i rozumiesz nasze zasady używania plików cookie i zasady ochrony prywatności.
Licensed under cc by-sa 3.0 with attribution required.