BolusIntent.swift 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. import AppIntents
  2. import Foundation
  3. import Intents
  4. import Swinject
  5. @available(iOS 16.0,*) struct BolusIntent: AppIntent {
  6. // Title of the action in the Shortcuts app
  7. static var title = LocalizedStringResource("Enact Bolus", table: "ShortcutsDetail")
  8. // Description of the action in the Shortcuts app
  9. static var description = IntentDescription(.init("Allow to send a bolus to the app", table: "ShortcutsDetail"))
  10. internal var bolusRequest: BolusIntentRequest
  11. init() {
  12. bolusRequest = BolusIntentRequest()
  13. }
  14. @Parameter(
  15. title: LocalizedStringResource("Amount", table: "ShortcutsDetail"),
  16. description: LocalizedStringResource("Bolus amount in U", table: "ShortcutsDetail"),
  17. controlStyle: .field,
  18. inclusiveRange: (lowerBound: 0, upperBound: 200),
  19. requestValueDialog: IntentDialog(LocalizedStringResource(
  20. "What is the value of the bolus amount in insulin units ?",
  21. table: "ShortcutsDetail"
  22. ))
  23. ) var bolusQuantity: Double
  24. @Parameter(
  25. title: LocalizedStringResource("Confirm Before applying", table: "ShortcutsDetail"),
  26. description: LocalizedStringResource("If toggled, you will need to confirm before applying", table: "ShortcutsDetail"),
  27. default: true
  28. ) var confirmBeforeApplying: Bool
  29. static var parameterSummary: some ParameterSummary {
  30. When(\.$confirmBeforeApplying, .equalTo, true, {
  31. Summary("Applying \(\.$bolusQuantity) U ", table: "ShortcutsDetail") {
  32. \.$confirmBeforeApplying
  33. }
  34. }, otherwise: {
  35. Summary("Immediately applying \(\.$bolusQuantity) U", table: "ShortcutsDetail") {
  36. \.$confirmBeforeApplying
  37. }
  38. })
  39. }
  40. @MainActor func perform() async throws -> some ProvidesDialog {
  41. do {
  42. let amount: Double = bolusQuantity
  43. let bolusFormatted = amount.formatted()
  44. if confirmBeforeApplying {
  45. try await requestConfirmation(
  46. result: .result(
  47. dialog: IntentDialog(LocalizedStringResource(
  48. "Are you sure you want to bolus \(bolusFormatted) U of insulin ?",
  49. table: "ShortcutsDetail"
  50. ))
  51. )
  52. )
  53. }
  54. let finalBolusDisplay = try await bolusRequest.bolus(amount)
  55. return .result(
  56. dialog: IntentDialog(finalBolusDisplay)
  57. )
  58. } catch {
  59. throw error
  60. }
  61. }
  62. }