Swift 3文件复制错误

时间:2017-12-08 17:58:02

标签: swift url nsfilemanager

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

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

1 个答案:

答案 0 :(得分:0)

Documentation

  

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

您需要将文件名"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 {
   ...
}