Skip to content

Instantly share code, notes, and snippets.

@justinmeiners
Last active January 14, 2022 23:41
Show Gist options
  • Save justinmeiners/6acff83ae434c4b3d855a0fbc9b7214e to your computer and use it in GitHub Desktop.
Save justinmeiners/6acff83ae434c4b3d855a0fbc9b7214e to your computer and use it in GitHub Desktop.
iOS swift FileManager remove/delete file only if it exists. "No such file or directory" fix.
// Most implementations first check if the file exists, and then do the remove.
// This is subject to race conditions and requires accessing the file system twice.
// A better solution is to ignore that particular exception.
extension FileManager {
func removeItemIfExists(at url: URL) throws {
func isDoesNotExist(error: NSError) -> Bool {
return error.domain == NSPOSIXErrorDomain && error.code == ENOENT
}
func isFailedToRemove(error: NSError) -> Bool {
return error.domain == NSCocoaErrorDomain && error.code == 4
}
do {
try removeItem(at: url)
}
catch let error as NSError {
if isFailedToRemove(error: error),
let underlying = error.userInfo[NSUnderlyingErrorKey] as? NSError,
isDoesNotExist(error: underlying)
{
// ignore. The file didn't exist.
}
else {
// a different error which should be handled
throw error
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment