I'm calling the openDocument environment value to open a document with a document-based application. Seeing its definition, it's @Environment @MainActor.
import SwiftUI
struct ContentView: View {
@Binding var document: TextDocument
@Environment(\.openDocument) private var openDocument
var body: some View {
VStack {
}
.onAppear {
Task {
await loadBookmarks()
}
}
}
}
extension ContentView {
@MainActor
func loadBookmarks() async {
for bookmarkItem in bookmarkViewModel.bookmarkItems {
if let _ = resolveBookmark(bookmarkData: bookmarkItem.bookmarkData) { // resolving a security-scoped bookmark
do {
try await openDocument(at: bookmarkItem.bookmarkURL)
} catch {
print("\(error.localizedDescription)")
}
}
}
}
}
If I use the openDocument environment value, the application will open a document but crash. The Xcode console says
should only be called in the main thread
The loadBookmarks function is already marked MainActor. What else can I do to resolve this main thread issue? Thanks.