Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Swift:无法将文件复制到新创建的文件夹_Swift_Nsfilemanager - Fatal编程技术网

Swift:无法将文件复制到新创建的文件夹

Swift:无法将文件复制到新创建的文件夹,swift,nsfilemanager,Swift,Nsfilemanager,我正在用Swift构建一个简单的程序,它应该将具有特定扩展名的文件复制到不同的文件夹中。如果该文件夹存在,程序将仅将其复制到该文件夹中;如果该文件夹不存在,程序必须先创建该文件夹 let newMTSFolder = folderPath.stringByAppendingPathComponent("MTS Files") if (!fileManager.fileExistsAtPath(newMTSFolder)) { fileManager.createDirectoryAtP

我正在用Swift构建一个简单的程序,它应该将具有特定扩展名的文件复制到不同的文件夹中。如果该文件夹存在,程序将仅将其复制到该文件夹中;如果该文件夹不存在,程序必须先创建该文件夹

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.")
        }
    }
}
运行此代码将正确识别MTS文件,但会导致“添加失败…”,我做错了什么?

来自:

dstPath

放置
srcPath
副本的路径。这条路必须走 在新位置包含文件或目录的名称

您必须将文件名附加到
copyItemAtPath()
call(为Swift 3及更高版本更新了代码)

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