Search code examples
swiftnsfilemanager

Swift: failing to copy files to a newly created folder


I'm building a simple program in Swift, it should copy files with a certain extension to a different folder. If this folder exist the program will just copy them in the folder, if the folder doesn't exist, the program has to make it first.

let newMTSFolder = folderPath.stringByAppendingPathComponent("MTS Files")

if (!fileManager.fileExistsAtPath(newMTSFolder)) {
    fileManager.createDirectoryAtPath(newMTSFolder, withIntermediateDirectories: false, attributes: nil, error: nil)
}

while let element = enumerator.nextObject() as? String {
    if element.hasSuffix("MTS") { // checks the extension
        var fullElementPath = folderPath.stringByAppendingPathComponent(element)

        println("copy \(fullElementPath) to \(newMTSFolder)")

        var err: NSError?
        if NSFileManager.defaultManager().copyItemAtPath(fullElementPath, toPath: newMTSFolder, error: &err) {
            println("\(fullElementPath) file added to the folder.")
        } else {
            println("FAILED to add \(fullElementPath) to the folder.")
        }
    }
}

Running this code will correctly identify the MTS files but then result in a "FAILED to add...", what am I doing wrong?


Solution

  • From the copyItemAtPath(...) documentation:

    dstPath
    The path at which to place the copy of srcPath. This path must include the name of the file or directory in its new location. ...

    You have to append the file name to the destination directory for the copyItemAtPath() call (code updated for Swift 3 and later)

    let srcURL = URL(fileURLWithPath: fullElementPath)
    let destURL = URL(fileURLWithPath: newMTSFolder).appendingPathComponent(srcURL.lastPathComponent)
    
    do {
        try FileManager.default.copyItem(at: srcURL, to: destURL)
    } catch {
        print("copy failed:", error.localizedDescription)
    }