SwiftUI fileExporter在DocumentGroup的工具栏修饰符中用作按钮修饰符时不存在



在iOS中的特定场景下,我很难在SwiftUI中显示.fileExporter:当它用作DocumentGroup场景工具栏中的按钮修饰符时。

请参阅下面显示问题的代码。

预期结果:当用户按下";保存文件";按钮,.fileExporter应出现,并提示用户保存文件。

实际结果:即使状态变量已更改并且文档不是nil,也不会发生任何事情。

问题出现在iOS 15.0模拟器以及使用硬件的iOS 15.1和15.2中。这不会在macOS 12.0中出现

其他人有这个问题吗?是否有已知的解决方法?


import SwiftUI
@main
struct myApp: App {

@State private var showingFileExporter = false
var body: some Scene {
DocumentGroup(newDocument: myDocument()) { file in
ContentView(document: file.$document)
.toolbar {
Button("Save File") {
showingFileExporter = true
}
.fileExporter(isPresented: $showingFileExporter,
document: file.document,
contentType: UTType.exampleText) { result in
}
}
}
}
}

import UniformTypeIdentifiers
extension UTType {
static var exampleText: UTType {
UTType(importedAs: "com.example.plain-text")
}
}
struct myDocument: FileDocument {
var text: String
init(text: String = "Hello, world!") {
self.text = text
}
static var readableContentTypes: [UTType] { [.exampleText] }
init(configuration: ReadConfiguration) throws {
guard let data = configuration.file.regularFileContents,
let string = String(data: data, encoding: .utf8)
else {
throw CocoaError(.fileReadCorruptFile)
}
text = string
}

func fileWrapper(configuration: WriteConfiguration) throws -> FileWrapper {
let data = text.data(using: .utf8)!
return .init(regularFileWithContents: data)
}
}

struct ContentView: View {
@Binding var document: myDocument
var body: some View {
TextEditor(text: $document.text)
}
}

我的fileImporter刚刚遇到了同样的问题,如果你把它从.toolbar上下文中移出,它确实可以工作

这是我的代码:

.toolbar {
Button("Import") {
presentImporter.toggle()
}
}
.fileImporter(isPresented: $presentImporter, allowedContentTypes: [.mp3]) { result in
switch result {
case .success(let url):
print(url)

let newBook = Book(context: viewContext)
newBook.name = "(url.lastPathComponent)"
newBook.url = url
newBook.origin = playlist.self

try? viewContext.save()
let _ = print("New book", newBook.name as Any)
let _ = print("inside", newBook.origin as Any)

case .failure(let error):
print(error)
}
}

最新更新