Swift: failing to copy files to a newly created folder

本小妞迷上赌 提交于 2019-12-17 09:52:52

问题


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?


回答1:


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.

Something like (untested):

let destPath = newMTSFolder.stringByAppendingPathComponent(element.lastPathComponent)
if NSFileManager.defaultManager().copyItemAtPath(fullElementPath, toPath: destPath, error: &err) {
     // ...

Update for Swift 3/4:

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


来源:https://stackoverflow.com/questions/25291115/swift-failing-to-copy-files-to-a-newly-created-folder

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!