114

我想从我的应用文档目录中删除图像。我为删除图像而编写的代码是:

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

它的部分工作。此代码从目录中删除文件,但是当我检查目录中的内容时,它仍然在那里显示图像名称。我想从目录中完全删除该文件。我应该在代码中更改什么来做同样的事情?谢谢

4

10 回答 10

240

我检查了你的代码。它对我有用。使用以下修改后的代码检查您遇到的任何错误

- (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]);
  }
}
于 2013-02-22T06:29:24.547 回答
56

斯威夫特 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)
  }}

感谢@Anil Varghese,我在 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)
  }
}
于 2014-12-23T21:37:30.787 回答
11

斯威夫特 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")
            }
        }
    }
}
于 2016-02-02T12:06:02.873 回答
9

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

此方法可以删除所有本地文件

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)")
        }
    }
于 2018-08-01T10:29:10.107 回答
5

与其将错误设置为 NULL,不如将其设置为

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

这会告诉你它是否真的在删除文件

于 2013-02-22T06:20:56.790 回答
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");
    }
}
于 2016-06-03T05:07:52.457 回答
2
    NSError *error;
    [[NSFileManager defaultManager] removeItemAtPath:new_file_path_str error:&error];
    if (error){
        NSLog(@"%@", error);
    }
于 2014-08-19T15:54:53.200 回答
2

FreeGor 版本转换为 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")
            }
        }
    }
}
于 2018-02-18T17:12:06.670 回答
0

如果您对现代 api 方式感兴趣,避免 NSSearchPath 和过滤文档目录中的文件,在删除之前,您可以这样做:

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)")
   }
}
于 2017-12-15T14:36:38.920 回答
0

您可以使用 NSFileManager.defaultManager().isDeletableFileAtPath(PathName) 来双重保护您的文件删除到目前为止,您必须使用 do{}catch{},因为旧的错误方法不再有效。isDeletableFileAtPath() 不是“抛出”(即“public func removeItemAtPath(path: String) throws”)所以它不需要 do...catch

let killFile = NSFileManager.defaultManager()

            if (killFile.isDeletableFileAtPath(PathName)){


                do {
                  try killFile.removeItemAtPath(arrayDictionaryFilePath)
                }
                catch let error as NSError {
                    error.description
                }
            }
于 2016-02-09T21:14:42.840 回答