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?
From the copyItemAtPath(...)
documentation:
dstPath
The path at which to place the copy ofsrcPath
. 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)
}
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