[英]Failing to copy file from Bundle to Documents Directory Subfolder
I have created a Documents Directory
subfolder with the following code: 我用以下代码创建了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)")
}
}
Doing this the subfolder is created as expected. 这样做将按预期方式创建子文件夹。 I prove that by printing the documents directory
content and it shows the HTML
folder/file 我通过打印documents directory
内容来证明它显示了HTML
文件夹/文件
Then I am trying to copy another file that exists in the app Bundle
to this created subfolder but somehow I get an error saying that the specific file couldn't be copied to Documents
because an item with the same name already exists. 然后,我试图将应用程序Bundle
中存在的另一个文件复制到此创建的子文件夹中,但是由于某种原因,我已经收到一条错误消息,指出该特定文件无法复制到Documents
因为存在相同名称的项目。
This is confusing because even on a newly installation, without any copied file it says the file exists there but if I print the subfolder contents nothing is shown. 这是令人困惑的,因为即使在新安装的设备上也没有任何复制的文件,它说该文件存在于其中,但是如果我打印子文件夹的内容,则不会显示任何内容。
I'm trying to copy the file from the bundle
sandbox with the following code: 我正在尝试使用以下代码从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)
}
}
}
}
What am I doing wrong here? 我在这里做错了什么?
Regards. 问候。
You need to create a full path, including the filename. 您需要创建一个完整路径,包括文件名。
Change: 更改:
let filePath = tDocumentDirectory.appendingPathComponent("HTML")
to: 至:
let filePath = tDocumentDirectory.appendingPathComponent("HTML").appendingPathComponent(cssURL.lastPathComponent)
And the above use of lastPathComponent
can be made possible by changing: 并且可以通过更改来实现对lastPathComponent
的上述使用:
guard let cssPath = Bundle.main.path(forResource: "swiss", ofType: ".css") else {
to: 至:
guard let cssURL = Bundle.main.url(forResource: "swiss", withExtension: "css") else {
And of course use cssURL.path
in the call to copyItem
. 当然,使用cssURL.path
在调用copyItem
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.