Error deleting contents in directory - Domain=NSCocoaErrorDomain Code=4 | Domain=NSPOSIXErrorDomain Code=2 “No such file or directory”

∥☆過路亽.° 提交于 2019-12-06 11:29:42

nextObject() of (NS)DirectoryEnumerator returns always the full path / url of the enumerated items, an additional concatenation breaks the path. Aside form that concatenating URL and String with String Interpolation to pass it as path parameter doesn't work at all.

I recommend to use the URL related API anyway

let fileManager = FileManager.default
do {
    let url = try fileManager.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
    if let enumerator = fileManager.enumerator(at: url, includingPropertiesForKeys: nil) {
        while let fileURL = enumerator.nextObject() as? URL {
            try fileManager.removeItem(at: fileURL)
        }
    }
}  catch  {
    print(error)
}
Martian2049

Just to make it clear:

let addr = one["resourceAddr"] as! String
do {
   try FileManager.default.removeItem(at: URL(string:addr)!)
} catch let error as NSError {
    print("error: ", error.localizedDescription)
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!