Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
530 views
in Technique[技术] by (71.8m points)

nsfilemanager - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...