无法将文件从Bundle复制到Documents Directory子文件夹

时间:2017-12-10 00:29:59

标签: ios swift bundle nsdocumentdirectory

我创建了一个Documents Directory子文件夹,其中包含以下代码:

fileprivate func createFolderOnDocumentsDirectoryIfNotExists() {
    let folderName = "HTML"
    let fileManager = FileManager.default
    if let tDocumentDirectory = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first {
        let filePath =  tDocumentDirectory.appendingPathComponent("\(folderName)")
        if !fileManager.fileExists(atPath: filePath.path) {
            do {
                try fileManager.createDirectory(atPath: filePath.path, withIntermediateDirectories: true, attributes: nil)
            } catch {
                print("Couldn't create document directory")
            }
        }
        print("Document directory is \(filePath)")
    }
}

执行此操作后,子文件夹将按预期创建。我通过打印documents directory内容证明了它显示了HTML文件夹/文件

然后我尝试将应用程序Bundle中存在的另一个文件复制到此创建的子文件夹但不知何故我收到一条错误消息,指出无法将特定文件复制到Documents,因为项目具有相同名称已存在。

这很令人困惑,因为即使在新安装时,没有任何复制文件,它表示该文件存在,但如果我打印子文件夹内容则不会显示任何内容。

我正在尝试使用以下代码从bundle沙箱中复制文件:

fileprivate func copyCSSFileToHTMLFolder() {
    guard let cssPath = Bundle.main.path(forResource: "swiss", ofType: ".css") else {
        print("css not found -- returning")
        return
    }
    let fileManager = FileManager.default

    if let tDocumentDirectory = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first {
        let filePath =  tDocumentDirectory.appendingPathComponent("HTML")
        if fileManager.fileExists(atPath: filePath.path) {
            do {
                try fileManager.copyItem(atPath: cssPath, toPath: filePath.path)
            } catch {
                print("\nFailed to copy css to HTML folder with error:", error)
            }
        }
    }
}

我在这里做错了什么?

问候。

1 个答案:

答案 0 :(得分:1)

您需要创建一个完整路径,包括文件名。

变化:

let filePath =  tDocumentDirectory.appendingPathComponent("HTML")

为:

let filePath =  tDocumentDirectory.appendingPathComponent("HTML").appendingPathComponent(cssURL.lastPathComponent)

通过更改:

可以实现lastPathComponent的上述用法
guard let cssPath = Bundle.main.path(forResource: "swiss", ofType: ".css") else {

为:

guard let cssURL = Bundle.main.url(forResource: "swiss", withExtension: "css") else {

当然,在cssURL.path的调用中使用copyItem

相关问题