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

标签 swift nsfilemanager

我正在用 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 文件,但随后会导致“添加失败...”,我做错了什么?

最佳答案

来自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. ...

您必须将文件名附加到目标目录中 copyItemAtPath() 调用(针对 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)
}

关于Swift:无法将文件复制到新创建的文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47845268/

相关文章:

objective-c - 在继续 [Obj-C] 之前检查文件是否存在

copy - iOS9 NSFileManager 请求在 Documents 目录中保存文件的权限

iphone - 将文件下载到 iPhone 中的文件夹

ios - 如何在静态函数中使用 UITapGestureRecognizer 向标签添加点击功能

ios - 即使将重复间隔设置为工作日,UILocalNotification 也会每天触发

iphone - 在 iPhone 的 Library 目录中创建文件

ios - 在 Swift 中设置 Realm 的位置

ios - 来自 2 个节点的 Firebase 查询

ios - 在 TraitCollectionDidChange 之后重组 Toolbar 和 NavigationBar

ios - Swift 3 中的 DISPATCH_QUEUE_T