我需要一個包含檔案和檔案夾的 FileWrapper。該檔案是單個檔案,該檔案夾用于寫入影像。
該檔案夾還可以包含一些子檔案夾。我有一個作業代碼,但問題是當檔案被保存時,檔案夾被重寫,這會洗掉我的影像和子檔案夾。
我很確定這與它有關,func fileWrapper(configuration: WriteConfiguration) throws -> FileWrapper但我需要一些對 FileWrappers 有更多經驗的人的幫助。
這是我的代碼:
struct MyProject: FileDocument {
var myFile: MyFile
static var readableContentTypes: [UTType] { [.myf] }
init(myFile: MyFile = MyFile() {
self.myFile = myFile
}
init(configuration: ReadConfiguration) throws {
let decoder = JSONDecoder()
guard let data = configuration.file.fileWrappers?["MYFProject"]?.regularFileContents else {
throw CocoaError(.fileReadCorruptFile)
}
do {
self.myFile = try decoder.decode(MyFile.self, from: data)
} catch {
throw error
}
}
func fileWrapper(configuration: WriteConfiguration) throws -> FileWrapper {
let encoder = JSONEncoder()
do {
let data = try encoder.encode(myFile)
let mainDirectory = FileWrapper(directoryWithFileWrappers: [:])
let myfWrapper = FileWrapper(regularFileWithContents: data)
let imagesWrapper = FileWrapper(directoryWithFileWrappers: [:])
let imageSubFolder = FileWrapper(directoryWithFileWrappers: [:])
for numberString in myFile.numbers {
imageSubFolder.preferredFilename = numberString
imagesWrapper.addFileWrapper(imageSubFolder)
}
myfWrapper.preferredFilename = "MYFProject"
mainDirectory.addFileWrapper(myfWrapper)
imagesWrapper.preferredFilename = "MYFImages"
mainDirectory.addFileWrapper(imagesWrapper)
return mainDirectory
} catch {
throw error
}
}
}
我使用此路徑將影像寫入。
func getSubFolderImageFolder(documentPath: URL, subFolder: String) -> URL {
let sfProjectPath = documentPath.appendingPathComponent("MYFImages").appendingPathComponent(subFolder)
if !FileManager.default.fileExists(atPath: sfProjectPath.path) {
do {
try FileManager.default.createDirectory(atPath: sfProjectPath.path, withIntermediateDirectories: false, attributes: nil)
return sfProjectPath
} catch {
fatalError(error.localizedDescription)
}
}
else {
return sfProjectPath
}
}
提前致謝!
uj5u.com熱心網友回復:
您的getSubFolderImageFolder函式不適用于檔案包裝器。您必須使用這些FileWrapper方法在檔案包裝器中創建檔案夾和檔案。
要將子檔案夾添加到影像檔案夾,請按照imagesWrapper為影像創建檔案夾的方式創建目錄檔案包裝器。添加子檔案夾作為影像檔案夾的子檔案夾。
let imageSubFolder = FileWrapper(directoryWithFileWrappers: [:])
imagesWrapper.addFileWrapper(imageSubFolder)
您必須為每個子檔案夾創建一個目錄檔案包裝器。我注意到在您更新的代碼中,您只有一個子檔案夾檔案包裝器。只有一個子檔案夾檔案包裝器,您無法將影像檔案存盤在正確的子檔案夾中。
要添加影像,首先將每個影像轉換為Data物件。為每個影像創建一個常規檔案包裝器,將影像資料作為引數傳遞給regularFileWithContents. 呼叫addFileWrapper以將影像檔案添加到適當的檔案夾。
let imageFile = FileWrapper(regularFileWithContents: imageData)
imageFile.preferredFilename = "ImageFilename" // Replace with your filename.
imagesWrapper.addFileWrapper(imageFile)
在您的情況下,影像子檔案夾將呼叫addFileWrapper以添加影像。影像檔案的目標呼叫addFileWrapper.
您可以在以下文章中找到有關檔案包裝器的更多詳細資訊:
在 SwiftUI 應用程式中使用檔案包裝器
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/366175.html
