[英]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.