Adding this because this question pops up in Google and the other answers use an API that they perhaps shouldn't in this context.
It's important to note this in the FileExists(atPath:) docs:
Attempting to predicate behavior based on the current state of the file system or a particular file on the file system is not recommended. Doing so can cause odd behavior or race conditions. It’s far better to attempt an operation (such as loading a file or creating a directory), check for errors, and handle those errors gracefully than it is to try to figure out ahead of time whether the operation will succeed. For more information on file-system race conditions, see Race Conditions and Secure File Operations in Secure Coding Guide.
Also, from the createDirectory(atPath:withIntermediateDirectories:attributes:) docs:
Return Value
true if the directory was created, true if createIntermediates is set and the directory already exists, or false if an error occurred.
Attempting to create a new directory with the withIntermediateDirectories:
parameter set to true will not throw an error if that directory already exists, so you can safely use it even if the directory does already exist.
Skip the existence check, try to write the directory, then try to move the file:
func moveFile(from currentURL: URL, to targetURL: URL) {
// Get the target directory by removing the file component
let targetDir = targetURL.deletingLastPathComponent()
do {
try FileManager.default.createDirectory(at:targetDir, withIntermediateDirectories: true, attributes: nil)
} catch {
// Handle errors
}
do {
try FileManager.default.moveItem(at:currentURL, to: targetURL) }
catch {
// Handle errors
}
}
currentPath
is misleading, it String contains something like: "/Documents/test.plist", it includes the full path and the filename. That's whycreateDirectoryAtPath
isn't working for me, because in this case it creates a directory named "test.plist". – Flint