在 iOS 的特定场景下,我无法让 .fileExporter 在 SwiftUI 中呈现:在 DocumentGroup 场景的工具栏中用作按钮修饰符时。
请参阅下面显示问题的代码。
预期结果: 当用户按下“保存文件”按钮时,.fileExporter 应出现,并提示用户保存文件。
实际结果: 即使状态变量发生更改并且文档不为零,似乎也没有发生任何事情。
问题出现在 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)
}
}
Run Code Online (Sandbox Code Playgroud)
小智 4
我的 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)
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
746 次 |
| 最近记录: |