ApplyTempPresetIntent.swift 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. import AppIntents
  2. import Foundation
  3. @available(iOS 16.0, *) struct ApplyTempPresetIntent: AppIntent {
  4. // Title of the action in the Shortcuts app
  5. static var title: LocalizedStringResource = "Apply a temporary target"
  6. // Description of the action in the Shortcuts app
  7. static var description = IntentDescription("Enable a temporary target")
  8. internal var intentRequest: TempPresetsIntentRequest
  9. init() {
  10. intentRequest = TempPresetsIntentRequest()
  11. }
  12. @Parameter(title: "Preset") var preset: TempPreset?
  13. @Parameter(
  14. title: "Confirm Before applying",
  15. description: "If toggled, you will need to confirm before applying",
  16. default: true
  17. ) var confirmBeforeApplying: Bool
  18. static var parameterSummary: some ParameterSummary {
  19. When(\ApplyTempPresetIntent.$confirmBeforeApplying, .equalTo, true, {
  20. Summary("Applying \(\.$preset)") {
  21. \.$confirmBeforeApplying
  22. }
  23. }, otherwise: {
  24. Summary("Immediately applying \(\.$preset)") {
  25. \.$confirmBeforeApplying
  26. }
  27. })
  28. }
  29. private func decimalToTimeFormattedString(decimal: Decimal) -> String {
  30. let timeInterval = TimeInterval(decimal * 60) // seconds
  31. let formatter = DateComponentsFormatter()
  32. formatter.allowedUnits = [.hour, .minute]
  33. formatter.unitsStyle = .brief // example: 1h 10 min
  34. return formatter.string(from: timeInterval) ?? ""
  35. }
  36. @MainActor func perform() async throws -> some ProvidesDialog {
  37. do {
  38. let presetToApply: TempPreset
  39. if let preset = preset {
  40. presetToApply = preset
  41. } else {
  42. presetToApply = try await $preset.requestDisambiguation(
  43. among: intentRequest.fetchAndProcessTempTargets(),
  44. dialog: "Select Temporary Target"
  45. )
  46. }
  47. let displayName: String = presetToApply.name
  48. if confirmBeforeApplying {
  49. try await requestConfirmation(
  50. result: .result(dialog: "Confirm to apply temporary target '\(displayName)'")
  51. )
  52. }
  53. if await intentRequest.enactTempTarget(presetToApply) {
  54. return .result(
  55. dialog: IntentDialog(
  56. LocalizedStringResource(
  57. "TempTarget '\(presetToApply.name)' applied",
  58. table: "ShortcutsDetail"
  59. )
  60. )
  61. )
  62. } else {
  63. return .result(
  64. dialog: IntentDialog(
  65. LocalizedStringResource(
  66. "TempTarget '\(presetToApply.name)' failed",
  67. table: "ShortcutsDetail"
  68. )
  69. )
  70. )
  71. }
  72. } catch {
  73. throw error
  74. }
  75. }
  76. }