繁体   English   中英

无法将文件从捆绑包复制到文档目录子文件夹

[英]Failing to copy file from Bundle to Documents Directory Subfolder

我用以下代码创建了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)
            }
        }
    }
}

我在这里做错了什么?

问候。

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

更改:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM