Swift 3 文件复制错误

Posted

技术标签:

【中文标题】Swift 3 文件复制错误【英文标题】:Swift 3 File copy error 【发布时间】:2017-12-08 17:58:01 【问题描述】:

我正在尝试将 .plist 的副本复制到 Documents 文件夹中。 我有这个代码,但我得到“文件复制错误”。

let srcPath = Bundle.main.path(forResource: "Gameboard", ofType: "plist")
//let path = Bundle.main.resourcePath!
let path = String(describing: FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first)
print(srcPath)
print(path)
do 
    //Copy the project plist file to the documents directory.
    try FileManager.default.copyItem(atPath: srcPath!, toPath: path)
 catch 
    print("File copy error!")

【问题讨论】:

***.com/q/25291115/1187415 的可能重复项。 FileManager.default.copyItem(atPath:, toPath:) 不会抛出可以为您提供有关该问题的提示的错误? 切勿使用String(describing)URL 转换为String。使用正确的URL 方法(在本例中为path)。 【参考方案1】:

Documentation:

dstPath 放置 srcPath 副本的路径。此路径必须在其新位置包含文件或目录的名称。此参数不能为 nil。

您需要将文件名"Gameboard.plist"附加到目标路径:

let srcUrl = Bundle.main.url(forResource: "Gameboard", ofType: "plist")
let documentsUrl = FileManager.default.urls(
    for: .documentDirectory,
    in: .userDomainMask
).first!
let destinationUrl = documentsUrl.appendingPathComponent(
   "Gameboard.plist",   // or srcUrl.lastPathComponent
    isDirectory: false
)

do 
   try FileManager.default.copyItem(at: srcUrl, to: destinationUrl)
 catch 
   ...

【讨论】:

以上是关于Swift 3 文件复制错误的主要内容,如果未能解决你的问题,请参考以下文章

如何避免swift 3中的错误无效重新声明? [复制]

如何在 Swift 项目中管理文件夹? [复制]

swift 3 Type 'Any' 没有下标成员? [复制]

Swift 3:公共访问修饰符和内部访问修饰符之间的区别? [复制]

从主包复制到应用程序支持 swift

swift编译器显示预期的声明错误? [复制]