AIFreeUsageManager.swift 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. import Foundation
  2. @MainActor
  3. @Observable
  4. final class AIFreeUsageManager {
  5. static let shared = AIFreeUsageManager()
  6. static let maxFreeUses = 3
  7. private static let usedCountKey = "AIFreeUsageManager.usedCount"
  8. private(set) var usedCount: Int
  9. var remainingUses: Int {
  10. max(0, Self.maxFreeUses - usedCount)
  11. }
  12. var hasExhaustedFreeUses: Bool {
  13. usedCount >= Self.maxFreeUses
  14. }
  15. func canUseFreeLiveAI(hasEverPurchasedPremium: Bool) -> Bool {
  16. !hasEverPurchasedPremium && remainingUses > 0
  17. }
  18. private init() {
  19. usedCount = UserDefaults.standard.integer(forKey: Self.usedCountKey)
  20. }
  21. func recordUse(for tool: AIHistoryToolKind) {
  22. guard usedCount < Self.maxFreeUses else { return }
  23. usedCount += 1
  24. persistUsedCount()
  25. }
  26. /// Restores the free AI quota for users who have never purchased premium (e.g. sandbox transaction reset).
  27. func resetFreeUses() {
  28. usedCount = 0
  29. persistUsedCount()
  30. }
  31. /// Permanently removes free AI access after a purchase or refund.
  32. func forfeitFreeUses() {
  33. usedCount = Self.maxFreeUses
  34. persistUsedCount()
  35. }
  36. private func persistUsedCount() {
  37. UserDefaults.standard.set(usedCount, forKey: Self.usedCountKey)
  38. }
  39. }