Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to move a file and create missing directories in OS X?

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?

like image 584
ixany Avatar asked Oct 02 '15 18:10

ixany


1 Answers

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

like image 107
Charles A. Avatar answered Nov 01 '22 13:11

Charles A.