I want to move a file, in OSX, to another directory:
func moveFile(currentPath currentPath: String, targetPath: String) {
let fileManager = NSFileManager.defaultManager()
do { try fileManager.moveItemAtPath(currentPath, toPath: targetPath) }
catch let error as NSError { print(error.description) }
}
Everything is working fine, except the case when the target-directory doesn't exist. I figured out that .isWritableFileAtPath
could be helpful.
However, in my declared function I use the full file path (including the filename).
How can I split the filename from the path or more in general: how can I force Swift to create the directory before moving the file if needed?
In the past I have solved this problem with code similar to the code below. Basically you just check to see if a file exists at the path representing the parent directory of the file you want to create. If it does not exist you create it and all folders above it in the path that don't exist as well.
func moveFile(currentPath currentPath: String, targetPath: String) {
let fileManager = NSFileManager.defaultManager()
let parentPath = (targetPath as NSString).stringByDeletingLastPathComponent()
var isDirectory: ObjCBool = false
if !fileManager.fileExistsAtPath(parentPath, isDirectory:&isDirectory) {
fileManager.createDirectoryAtPath(parentPath, withIntermediateDirectories: true, attributes: nil)
// Check to see if file exists, move file, error handling
}
else if isDirectory {
// Check to see if parent path is writable, move file, error handling
}
else {
// Parent path exists and is a file, error handling
}
}
You may also want to use the fileExistsAtPath:isDirectory: variant so you can handle other error cases. Same is true for
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With