【问题标题】:FileManager.default.removeItem not removing file [duplicate]FileManager.default.removeItem 不删除文件 [重复]
【发布时间】:2017-09-24 21:02:41
【问题描述】:

我正在尝试使用FileManager.default.removeItem 从文档目录中删除一个文件,但没有在模拟器上删除该文件。这是我的代码:

if let dir = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first {
            do{
                let path = dir.appendingPathComponent(file).absoluteString
                do{
                    try FileManager.default.removeItem(atPath:path)
                }catch{
                    print(error)
                }
            }
        }

但我总是失败。有谁知道为什么会失败?

【问题讨论】:

  • 但它正在删除设备上的文件?您是否确认 path 已设置并存在?
  • 让 path = dir.appendingPathComponent(file).path 试试这个

标签: ios swift swift3 nsfilemanager


【解决方案1】:

你可以这样写:

var filemanager = FileManager.default
let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory,.userDomainMask,true)[0] as NSString
let destinationPath = documentsPath.appendingPathComponent("Filename.jpg")
try! filemanager.removeItem(atPath: destinationPath)

【讨论】:

    【解决方案2】:

    absoluteString 是错误的 API,file:// 方案的正确属性是 path。

    最好的解决方案是使用URL相关的API

    let fileURL = dir.appendingPathComponent(file)
    

    ...

    try FileManager.default.removeItem(at: fileURL)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-10-30
      • 1970-01-01
      • 2012-01-06
      • 2020-03-20
      • 2012-06-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多