Well, I need more than a refresher course, since I've just been trying to understand how each piece of SwiftUI works when I come to it. I never been so stymied and angry at a language in all my 48 years of programming.
Here's the relevant code. Comments say what works and what doesn't:
@main
struct SpeakotronikApp: App {
@State public var contentView = ContentView();
@State var showFileImporter:Bool = false;
var body:some Scene {
WindowGroup {
self.contentView
.environment(langModel)
}
.commands {
CommandGroup(after:.newItem) {
Button("Import…") {
self.showFileImporter = true;
}
.fileImporter(isPresented:$showFileImporter, allowedContentTypes:[.text], allowsMultipleSelection:false) { result in
switch result {
case .success(let urls):
for url in urls {
// Tell the content view to read the file and add new terms that will be translated:
self.contentView.importTerms(url:url);
}
case .failure(let error):
print("Error selecting file: \(error.localizedDescription)");
}
}
}
}
}
}
struct ContentView: View {
@Environment(LangViewModel.self) private var langModel;
@State private var selectedLang:Locale.Language = ...a language...;
// This variable causes .translationTask to run when called from code contained in ContentView (.onChange), which works:
@State var sequenceTranslationConfig:TranslationSession.Configuration?;
var body: some View {
VStack {
...buttons and stuff...
}
.onChange(of:selectedLang) {
// Trigger the sequence translations to run:
sequenceTranslationConfig = .init(source:Locale.current.language, target:selectedLang, preferredStrategy:.highFidelity);
}
.translationTask(sequenceTranslationConfig) { session in
await langModel.translateSequence(using:session, terms:self.terms);
}
}
public func importTerms(url:URL)
{
// Gain temporary permission to read security-scoped sandbox files
guard url.startAccessingSecurityScopedResource() else { return }
// Defer release of the system permission
defer { url.stopAccessingSecurityScopedResource() }
do {
...read file and do stuff with it...
// Trigger my sequence translations to happen, which does NOT work:
sequenceTranslationConfig = .init(source:Locale.current.language, target:selectedLang, preferredStrategy:.highFidelity);
}
catch {
print("Error reading file: \(error.localizedDescription)")
}
}
}