Resolution
Incase anyone stumbles on this, here's our solution to "can't use if-statements in .translationTask(configuration)"
Originally I built a ViewModifier to switch between conditions (download only, or perform translation); but that didn't work for our use case. View Modifiers redraw the view causing TextEditors to lose their focus, which would not work for us.
I landed on making a second TranslationSession.Configuration one for checking if language is downloaded, one for performing the translation.
We check which to execute when the user taps the translate button:
Two Configurations
device owner is translating to
@State var configurationForDownloadCheck: TranslationSession.Configuration?
@State var configuration: TranslationSession.Configuration?
Check which to run
.onTapGesture {
Task {
// check if languages are downloaded and set control
var
let languagesFullyDownloaded = await
translationLanguageIsDownloaded(from:
nativeLanguageCode!, to: guestLanguageCode!)
performFullTranslate = languagesFullyDownloaded
// decide if we need can translate or need to
download first.
if performFullTranslate {
// send for translation work
performTranslation(from: nativeLanguageCode!, to:
guestLanguageCode!)
} else {
// send to check of Downloaded or not
downloadLanguages(from: nativeLanguageCode!, to:
guestLanguageCode!)
}
}
}
View Modifier (works, but not for our needs)
@available(iOS 18.0, *)
struct TaskTranslationSwitchModifier: ViewModifier {
@EnvironmentObject var textObject: TextObject
@Binding var configuration: TranslationSession.Configuration?
let performFullTranslate: Bool
@Binding var lastTranslation: String
// Callback for notifying about text changes
var onTextChanged: ((String) -> Void)?
func body(content: Content) -> some View {
if performFullTranslate {
content
.translationTask(configuration) { session in
print("greg: performing full translate")
Task { @MainActor in
do {
// prepare
try await session.prepareTranslation()
// send inputText to Translation API
let response = try await session.translate(textObject.inputText)
} catch {
print("Translate failed: \(error)")
}
}
}
} else {
content
.translationTask(configuration) { session in
print("greg: performing DL sheet ONLY!")
Task { @MainActor in
do {
// just prepare the DL sheet
try await session.prepareTranslation()
} catch {
print("Translate failed: \(error)")
}
}
}
}
}
}